I want to understand arguments of the constructor __init__
in Python.
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
I call the getone()
method:
print myObj.getone()
RESULT: Error 'getone()' takes no arguments (1given).
So I replace:
def getone(): return 1
with
def getone(self): return 1
RESULT:1 This is OK.
But getone()
method needs no arguments.
Do I have to use meaningless argument?
Here, the __init__() function will take two argument values at the time of the object creation that will be used to initialize two class variables, and another method of the class will be called to print the values of the class variables.
The __init__ method is the Python equivalent of the C++ constructor in an object-oriented approach. The __init__ function is called every time an object is created from a class. The __init__ method lets the class initialize the object's attributes and serves no other purpose. It is only used within classes.
The Default __init__ Constructor in C++ and Java. Constructors are used to initializing the object's state. The task of constructors is to initialize(assign values) to the data members of the class when an object of the class is created.
The self in keyword in Python is used to all the instances in a class. By using the self keyword, one can easily access all the instances defined within a class, including its methods and attributes. init. __init__ is one of the reserved methods in Python. In object oriented programming, it is known as a constructor.
In Python:
self
argument.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:
import sys class Num: max = sys.maxint def __init__(self,num): self.n = num def getn(self): return self.n @staticmethod def getone(): return 1 @classmethod def getmax(cls): return cls.max myObj = Num(3) # with the appropriate decorator these should work fine myObj.getone() myObj.getmax() myObj.getn()
That said, I would try to use @classmethod
/@staticmethod
sparingly. If you find yourself creating objects that consist of nothing but staticmethod
s the more pythonic thing to do would be to create a new module of related functions.
Every method needs to accept one argument: The instance itself (or the class if it is a static method).
Read more about classes in Python.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With