简体   繁体   中英

Super() class's attributes not inherited?

It seems the child class doesn't inherit the parent attributes, despite calling super().__init__(args) . I read

Python: subclass inherits super class attributes, but loses it's other attributes

and

Subclass is not inheriting the attributes of second Super Class

but I read the attributes should be inherited if called within super().__init__()

With the following code (3.10.1)

class interface(object):
    MEDIA = ('COPPER','FIBER')
    SPEED_COPPER = ('100', '1G', '2.5G', '5G', '10G')
    SPEED_FIBER =  ('10G', '25G', '40G', '100G')
    TYPE_L2 = ('ACCESS', 'TRUNK', 'HYBRID')
    
    def __init__(self, media = None, speed = None):
        self.media = media
        self.speed = speed
    
    def set_media(self):
        pass
    
    def is_copper(self):
        return self.media == 'COPPER'
    
    def is_fiber(self):
        return self.media == 'FIBER'

class copper_1G(interface):
    def __init__(self):
        super().__init__(media = 'COPPER', speed = '1G')

class generic_mod(object):
    def __init__(self, max_slots):
        self.slots = []
        self.max_slots = max_slots
        self.set_interfaces()
    
    def set_interfaces(self):
        if len(self.slots) < self.max_slots:
            for slot in range(0,self.max_slots):
                self.slots.append(copper_1G)


class module48_2(generic_mod):
    MAX_SLOTS = 48
    def __init__(self):
        super().__init__(self.MAX_SLOTS)
        self.set_interfaces()

>>> ff=module48_2()

>>> ff.slots[0].media
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'copper_1G' has no attribute 'media'
>>> ff.slots[0].speed
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'copper_1G' has no attribute 'speed'

the variable ff.slots[0] doesn't get the attributes media and speed of the parent class, though it gets the methods is_copper, is_fiber, etc etc...

class generic_mod(object):
   ...
    def set_interfaces(self):
        if len(self.slots) < self.max_slots:
            for slot in range(0,self.max_slots):
                self.slots.append(copper_1G)

self.slots.append(copper_1G) -> self.slots.append(copper_1G())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM