Pergunta

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!

Foi útil?

Solução

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):
    ....

Outras dicas

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
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top