-2

I have a class like following

class A:
     def __init__(self:A,size:int):
        self.size=size

when I input like:

>>>a=A(5)    
>>>a.size

it will come

>>>5

However when I input like:

>>>A.__init__(5)

it will have an missing argument 'size' error. I just don't understand that, Why I entered an init it still missing argument?

2 Answers2

3

__init__ needs a two arguments, self and an integer. Isn't that so simple?

For instance methods, Python will automatically pass a reference of the instance to your function. This is why all instance methods needs at least one argument, self.

This is your case:

>>> class A:
    def __init__(self)::

SyntaxError: invalid syntax
>>> class A:
    def __init__(self):
        print("Created!")


>>> a = A()
Created! #Success
>>> b = A.__init__()
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    b = A.__init__()
TypeError: __init__() missing 1 required positional argument: 'self'

Well, no wonder. __init__ needs an argument, but you're not passing anything.

However, if you insist on calling the function, you can just use another instance:

>>> b = A.__init__(a)
Created!

However this is just calling the function, and no new instance will be produced. b is None.

aIKid
  • 26,968
  • 4
  • 39
  • 65
1

__init__ is the constructor function in Python; read the answers to this question which explain in detail that concept.

In order to call a function (or "method") on a class in Python you need a classmethod; this answer explains the role of classmethod vs instance methods in Python.

The main distinction is that:

  • for class methods the class is passed as the first argument to the classmethod,
  • for instance methods, the instance itself is passed as the first argument to the method
Community
  • 1
  • 1
Joseph Victor Zammit
  • 14,760
  • 10
  • 76
  • 102