Op 15/03/2023 om 10:57 schreef scruel tao:
The following code won’t be allowed in Java, but in python, it works fine:
```python
class A:
     A = 3

     def __init__(self):
         print(self.A)

     def p(self):
         print(self.A)
         self.A += 1


class B(A):
     def __init__(self):
         print(2)
         self.p()
         super().__init__()


B()
```

How can I understand this? Will it be a problem?
Important: __init__ is not a constructor, like you have for example in C++. I don't know Java, but it seems plausible it works somewhat like C++ in this regard. Python does it differently: when you create an instance, the instance is fully created/constructed even before __init__ is called. __init__ is purely an initializer: you can use to initialize the things you want to initialize.

Back to your example: it works because A is a class-level attribute, which is initialized independently from __init__. If you make it an instance attribute, like below, things stop working:

    class A:
        def __init__(self):
            self.A = 3
            print(self.A)

        def p(self):
            print(self.A)
            self.A += 1


    class B(A):
        def __init__(self):
            print(2)
            self.p()
            super().__init__()


    B()
    print(A.A)

That fails like this:

    Traceback (most recent call last):
      File ".code.tio", line 18, in <module>
        B()
      File ".code.tio", line 14, in __init__
        self.p()
      File ".code.tio", line 7, in p
        print(self.A)
    AttributeError: 'B' object has no attribute 'A'

That's because now A is indeed initialized in A.__init__, so it doesn't exist before A.__init__ is called.

--
"Too often we hold fast to the cliches of our forebears. We subject all
facts to a prefabricated set of interpretations. Too often we enjoy the
comfort of opinion without the discomfort of thought."
        -- John F Kennedy

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to