2
class Car:
    pass

class Car():
    pass

What is the difference between these two? and,

a = Car

a = Car()

also, what is the difference between these two above?

Best Regards

1
  • Incidentally, you should usually inherit from object (eg. class Car(object)) to benefit from new-style classes. Commented May 6, 2011 at 2:10

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The second one has not been invalid syntax since 2.5.
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.