-2

I find when __init__ method lacks self parameter, only if there is no instantiation of this class, the compiler won't complain:

$ cat test.py
#!/usr/bin/python
class A():
    def __init__():
        print("A()")
$ ./test.py

But if there is a instantiation, the running time error will occur:

$ cat test.py
#!/usr/bin/python
class A():
    def __init__():
        print("A()")

A()
$ ./test.py
Traceback (most recent call last):
  File "./test.py", line 6, in <module>
    A()
TypeError: __init__() takes 0 positional arguments but 1 was given

Per my understanding, __init__() seems no use because it can't make any instance. So why doesn't the Python compiler enforce limitation such as when no self parameter in __init__ function, it will show error message? Is it reasonable? Or I miss something.

Ry-
  • 218,210
  • 55
  • 464
  • 476
Nan Xiao
  • 16,671
  • 18
  • 103
  • 164
  • You should modify the declaration of init from `def __init__():` to: `def __init__(self):` any class method should have `self` passed in as the first argument. – Nir Alfasi Aug 29 '17 at 02:48
  • The thing is, it's not an error when you don't include the self argument. The `__init__` just doesn't take an argument. BUT when you create an instance, Python implicitly calls the initializer WITH A PARAMETER, the instance. Thus the error. – Andrew Li Aug 29 '17 at 02:52
  • Why add more special cases? The closer `__init__` is to every other method, the better. Python will let you write `{**5}` and other things that don’t usually make sense, too, as long as you don’t run them. – Ry- Aug 29 '17 at 02:53

3 Answers3

0

__init__ is not a special name at compilation time.

It is possible to do things with the symbol A.__init__ other than invoke it by trying to construct an A, and I think it is possible to replace the unusable __init__ function with a different function at runtime prior to trying to construct an A.

The check for a correct number of arguments is made when __init__ is called, as it is for any other method.

Russell Borogove
  • 18,516
  • 4
  • 43
  • 50
0

it must be one argument at least, we call it "self" usually, so your Python code maybe have a small change

#!/usr/bin/python
class A(object):
    def __init__(self):
        print("A()")

A()
mayor
  • 11
  • 2
0

__init__ is the initialization of an already created instance of a class, therefore it needs self, just like every other class method. If you want to handle the creation of the class, that is the __new__ method. This seems like a good description.

Don't let the fact that python doesn't complain unless the method is called confuse you.

Brett Stottlemyer
  • 2,734
  • 4
  • 26
  • 38