0

This is how I am defining a class:

class Foo():
    def __init__(self, a, b):
        self.a = a
        self.b = b

So, when defining a class, the parameters to be passed for initialization are in the brackets immediately after the __init__ method.

My question is, what is supposed to be in, or what is the point of, the brackets just after the name of the class Foo.

I've looked around, but everything I have been able to find so far has either not actually put anything in those brackets, or has put something in, but hasn't explained why.

Thanks in advance!

2 Answers2

4

as @Christian mentioned, you can specify the superclass of Foo inside the brackets:

class Bar: pass
class Foo(Bar): #Foo is subclass of Bar now
    pass

by default, if Foo doesn't inherit any class, just omit the ():

class Foo: #this creates old-style classes in python2, which is not suggested
    ....

generally, we inherit from object (in python2) to create new-style classes when writing our custom classes:

class Foo(object):
    ....
Community
  • 1
  • 1
zhangxaochen
  • 32,744
  • 15
  • 77
  • 108
  • The defautl case of omitting the brackets is valid only for Python 3 - in Python 2 you should inherit all classes from "object", or risk having them misbehaving in strange ways. `class Bar(object):pass` – jsbueno Feb 19 '14 at 16:56
  • So in Python 2, inheritance wasn't possible? – 雨が好きな人 Feb 19 '14 at 17:09
  • @xander from where do you get that conclusion? – zhangxaochen Feb 19 '14 at 17:15
  • oh dear, sorry... Somehow misread @jsbueno's comment above. Oops. – 雨が好きな人 Feb 19 '14 at 17:17
  • @xander: of course it was (ad is) possible - you use the brackets after the class name the same way. We are talking about optionally suppressing the brackets if you are not inheriting of anything meaningful - which works for both versions. Only that will create undesirable "old style" classes in Python 2 due to backward compatibility issues with pre-python 2.2 code. – jsbueno Feb 19 '14 at 17:20
1

The parameters that go into the bracket after the class name is the name of the class to be inherited.

    class Parent:
        pass

    class Child(Parent):
        pass
HumptyDumptyEIZ
  • 374
  • 1
  • 6
  • 18