Mailing List Archive

We can call methods of parenet class without initliaze it?
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?
--
https://mail.python.org/mailman/listinfo/python-list
Re: We can call methods of parenet class without initliaze it? [ In reply to ]
On 15/03/23 10:57 pm, scruel tao wrote:
> How can I understand this? Will it be a problem?

I can't remember any details offhand, but I know I've occasionally
made use of the ability to do this. It's fine as long as the method
you're calling doesn't rely on anything you haven't initialised yet.

--
Greg


--
https://mail.python.org/mailman/listinfo/python-list
Re: We can call methods of parenet class without initliaze it? [ In reply to ]
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