When defining Python class, what is the difference between the presence or absence of parentheses?

Asked 2 years ago, Updated 2 years ago, 148 views

I have a question about how to write Python classes.

() What is the difference without it?

class class name():
class class name:

python python3 class

2022-09-30 16:23

1 Answers

There is no difference between them in terms of what classes they define.

If you read Python 3's grammar definition, you can see that this parenthesis is optional in class definitions.You can also write a list of classes from which to inherit the classes you want to define, but if you omit the inheritance source, it also says that object class will be the inheritance source.

Therefore, omit the parentheses

class C:
  pass

Even if you write it, write it in parentheses

class C():
  pass

Even if you write that, both of them are the same

class C(object):
  pass

The class is defined in the same way as the .

In fact, if you try the behavior in the interpreter, you will see that you define a class that inherits only the object class:

>>class C1:
...   pass
...
>> Class C2:
...   pass
...
>>>C1.__mro__
(<class'___main__.C1'>, <class' object'>)
>> C2.__mro__
(<class '__main__.C2'>, <class 'object'>)

Reference


2022-09-30 16:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.