Defining a class in Python
class Car:
pass
class Car():
pass
What is the difference between these two开发者_Python百科? and,
a = Car
a = Car()
also, what is the difference between these two above?
Best Regards
the first statement, a = Car
simply makes a
an alias to Car
class. So after you do that, you could do b = a()
and it would be the same as b = Car()
Once you attach the ()
at the end, it makes python actually initialize the class (either __call__
or just initialize, but you don't have to worry about that), and a becomes whatever
that's returned by Car()
, in this case, it is the class instance.
As for the difference between class Car:
and class Car():
. The second one is invalid syntax (edit: before 2.5, I would still say it's kind of bad style as there's no reason for it to be there if you're not inheritting). The reason you have the brackets there is when you need to inherit another class.
In the first snippet, the latter is invalid syntax in older versions of Python.
In the second snippet, the former binds a reference to the class, and the latter binds a reference to a new instance of the class.
精彩评论