+ 2
PYTHON: difference between defining a class with and without (empty) parentheses
Eg: class Spam: vs. class Spam():
3 Respuestas
+ 8
A class definition is a bit different from a function/method definition.
The parentheses in class definitions are for defining from which class you inherit. You don't write def in front of it, and when you inherit from 'object' which is the default you don't need the parentheses for the definition.
So you can write either:
class C():
Or:
class C:
Function/method definitions always take parentheses, even if you don't define parameters. If you don't use them, you'll get a SyntaxError.
Later, after the definition of a class/function/method in the code, just writing the name will point you to the class/function/method.
If you want to call or access any of these, you'll need (), [], . or whatever.
+ 5
The confusion may also stem from here:
When you have a function...
def f(x):
... the x stands for the parameter you are going to pass later when you call it:
print(f(5)+ f(7))
This on the other hand...
class C(D):
... does not specify a parameter, it just names the base class, the 'mommy' of your type.
When you later write...
C()
... you don't have to pass this D, because when you wrote C(), you're really calling the class's __init__ method, and this method defines how many arguments you'll have to pass.
+ 1
BTW a class can also be callable:
“If an object is callable it means you can use the round parentheses function call syntax on it and even pass in function call arguments. This is all powered by the __call__ dunder method.
Here’s an example of class defining a callable object:
class Adder:
def __init__(self, n):
self.n = n
def __call__(self, x):
return self.n + x
>>> plus_3 = Adder(3)
>>> plus_3(4)
7”
Excerpt From
Python Tricks: The Book
(Dan Bader)