__init__ and arguments in Python

PythonClassOopInstance

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

In Python:

  • Instance methods: require the self argument.
  • Class methods: take the class as a first argument.
  • Static methods: do not require either the instance (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 staticmethods the more pythonic thing to do would be to create a new module of related functions.

Solution 2 - Python

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.

Solution 3 - Python

The fact that your method does not use the self argument (which is a reference to the instance that the method is attached to) doesn't mean you can leave it out. It always has to be there, because Python is always going to try to pass it in.

Solution 4 - Python

In python you must always pass in at least one argument to class methods, the argument is self and it is not meaningless its a reference to the instance itself

Solution 5 - Python

The current object is explicitly passed to the method as the first parameter. self is the conventional name. You can call it anything you want but it is strongly advised that you stick with this convention to avoid confusion.

Solution 6 - Python

If you print(type(Num.getone)) you will get <class 'function'>.

It is just a plain function, and be called as usual (with no arguments):

Num.getone() # returns 1  as expected

but if you print print(type(myObj.getone)) you will get <class 'method'>.

So when you call getone() from an instance of the class, Python automatically "transforms" the function defined in a class into a method.

An instance method requires the first argument to be the instance object. You can think myObj.getone() as syntactic sugar for

Num.getone(myObj) # this explains the Error 'getone()' takes no arguments (1 given).

For example:

class Num:
    def __init__(self,num):
        self.n = num
    def getid(self):
        return id(self)

myObj=Num(3)

Now if you

print(id(myObj) == myObj.getid())    
# returns True

As you can see self and myObj are the same object

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYugo KamoView Question on Stackoverflow
Solution 1 - PythonstderrView Answer on Stackoverflow
Solution 2 - PythonFelix KlingView Answer on Stackoverflow
Solution 3 - PythonkindallView Answer on Stackoverflow
Solution 4 - PythonJordanView Answer on Stackoverflow
Solution 5 - PythonneilView Answer on Stackoverflow
Solution 6 - PythonlazosView Answer on Stackoverflow