Explain a caveat in the inheritance of a class in Python?


Warning: count(): Parameter must be an array or an object that implements Countable in /home/styllloz/public_html/qa-theme/donut-theme/qa-donut-layer.php on line 274
0 like 0 dislike
24 views
There is such code:

Copy Source | Copy HTML"'
Base class
"'class Component():  connects = []     "'
Method like. object to the collection
"'    def connect(self, object):        self.connects.append(object)  "'
Subclass 1
"'class Component1(Component):     def getData(self):        print 123  "'
Subclass 2
"'class Component2(Component):     def getData(self):        print 123   "'
Are instantiating
"'c1 = Component1()c2 = Component2() "'
Check the number of elements in subclass 2
"'print len(Component2.connects) # 0 "'
Added to the first subclass in an object collection
"'c1.connect(c2) "'
Check the number of elements in subclass 2
"'print len(Component2.connects) # 1



Why is changing the number of elements in the collection of the second object, if I add an element to the collection of the first object?
by | 24 views

3 Answers

0 like 0 dislike
connects is the attribute of the Component class, not the instance. Inheriting classes use the same memory address (id(c1.connects) == id(c2.connects))
Want to make it different — add to the description of Component1 and Component2 also connects = [] as you did for the base class.
by
0 like 0 dislike
Not
connects = []
\r
and
\r
def __init__(self)
connects = []
\r
PS the Indenting parser ate :(
by
0 like 0 dislike
are you sure that you need to connect it to the class and not the object?
\r
then, how to do this as a @classmethod and not a method.
and not to copy the line, you can create a attribute in the meta class:
\rMetaComp class(type): def __init__(cls,name,bases,kwargs): super(MetaComp, cls).__init__(name,bases,kwargs) cls.connects = [] # for each class, and heir to the bude your class Comp(object): __metaclass__ = MetaComp @classmethod def connect(cls,obj): cls.connects.append(obj) class Comp1(Comp): pass class Comp2(Comp): pass # each call adds to its connects: Comp.connect('foo') Comp1.connect('foo1') Comp2.connect('foo2')
by

Related questions

0 like 0 dislike
1 answer
asked Jun 3, 2019 by Surv16893
0 like 0 dislike
1 answer
0 like 0 dislike
2 answers
0 like 0 dislike
1 answer
0 like 0 dislike
7 answers
110,608 questions
257,186 answers
0 comments
26,933 users