Suppose I have this code:
class Num:
def __init__(self,num):
self.n = num
def getn(self):
return self.n
def getone():
return 1
myObj = Num(3)
print(myObj.getn()) # result: 3
But if I try print(myObj.getone()), I get an error: 'getone()' takes no arguments (1 given).
So I replace:
def getone():
return 1
with
def getone(self):
return 1
Now print(myObj.getone()) shows 1, as expected. But – getone() doesn’t need any arguments in order to just return 1. Do I have to use a meaningless argument?
In Python:
selfargument.self) or the class (cls) argument.__init__is a special function and without overriding__new__it will always be given the instance of the class as its first argument.An example using the builtin classmethod and staticmethod decorators:
That said, I would try to use
@classmethod/@staticmethodsparingly. If you find yourself creating objects that consist of nothing butstaticmethods the more pythonic thing to do would be to create a new module of related functions.