[python] __init__ and arguments in Python

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?

This question is related to python class oop instance

The answer is


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


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


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.


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.


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.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to class

String method cannot be found in a main class method Class constructor type in typescript? ReactJS - Call One Component Method From Another Component How do I declare a model class in my Angular 2 component using TypeScript? When to use Interface and Model in TypeScript / Angular Swift Error: Editor placeholder in source file Declaring static constants in ES6 classes? Creating a static class with no instances In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric Static vs class functions/variables in Swift classes?

Examples related to oop

How to implement a simple scenario the OO way When to use 'raise NotImplementedError'? PHP: cannot declare class because the name is already in use Python class input argument Call an overridden method from super class in typescript Typescript: How to extend two classes? What's the difference between abstraction and encapsulation? An object reference is required to access a non-static member Java Multiple Inheritance Why not inherit from List<T>?

Examples related to instance

best way to create object __init__ and arguments in Python What exactly is an instance in Java? Can we create an instance of an interface in Java? How to create a list of objects? What is the difference between an Instance and an Object? The difference between Classes, Objects, and Instances Python object deleting itself