Python subclass inheritance

I am trying to create several classes that inherit from a parent class that contains subclasses that inherit from other parent classes. But when I change the attributes in subclasses for any children, this change affects all child classes. I am looking to avoid the need to instantiate, as I use this function later.

There is a problem in the encoder below. The last line shows an unexpected result.

class SubclsParent(object):
    a = "Hello"

class Parent(object):
    class Subcls(SubclsParent):
        pass

class Child1(Parent):
    pass

class Child2(Parent):
    pass

Child1.Subcls.a # Returns "Hello"
Child2.Subcls.a # Returns "Hello"
Child1.Subcls.a = "Goodbye"
Child1.Subcls.a # Returns "Goodbye"
Child2.Subcls.a # Returns "Goodbye" / Should still return "Hello"!
+3
source share
5 answers

The behavior you see is exactly what you should expect. When you define a class

>>> class Foo(object): pass
...

, , - - , Foo. , , :

>>> Foo.a = 1
>>> Foo.a
1

, class .


, (, ), . , : . , , , , . ,

>>> class Foo(object):
...     class Bar(object): pass
...

Foo , Bar, . , Foo Bar . (, , :

>>> class Foo(object):
...     class Bar(object): pass
...
>>> class Foo(object): pass
...
>>> class Bar(object): pass
...
>>> Foo.Bar = Bar

.)

! , , ; !


, , , , .

- , . , . , , (). , ( ?) , .

- , . , , . - Page, , , contents , Page, , contents,

, Child1.Subcls.a Child2.Subcls.a . , !


, Java Python? , , , ?

- , , , , , , . , , Python, : .

+8

class SubclsParent(object):
    def __init__(self):
         self.a = "Hello"

SubclsParent.a , .

+3

Child1.Subcls, python , Child1.Subcls, Parent, , . Child2.Subcls. . Child1 Child2 , .

* , . *

, .

+1

Your problem is that when you access the attributes that you refer to, the inherited procedures that were created in the parent class all refer to the same variable. You can either make these instance variables or create attributes in child classes to obtain independent attributes.

+1
source

It is possible that you really want metaclasses .

0
source

Source: https://habr.com/ru/post/1792652/


All Articles