Home > OS >  How can I use multiple inheritance in case of manipulating variable value
How can I use multiple inheritance in case of manipulating variable value

Time:11-09

class Electronicdevice():
    Devices = 100
class Pocketgadgets(Electronicdevice):
    Pocketdevices = 40
class Phone(Pocketgadgets):
    #Phones = Devices - Pocketdevices
    pass

Samsung = Electronicdevice()
Galaxy = Pocketgadgets()
SamsungGalaxyS21 = Phone()

print(SamsungGalaxyS21.Devices)

I get the expected output in this case as 100, since it inherits the value from the Electronic device class.

But in case , I try to do the below ,I get an error "NameError: name 'Devices' is not defined"

class Electronicdevice():
    Devices = 100
class Pocketgadgets(Electronicdevice):
    Pocketdevices = 40
class Phone(Pocketgadgets):
    Phones = Devices - Pocketdevices
    pass

Samsung = Electronicdevice()
Galaxy = Pocketgadgets()
SamsungGalaxyS21 = Phone()

print(SamsungGalaxyS21.Phones)

Was expecting to get the value 60 as output.Can someone please help?

CodePudding user response:

You can try these solutions:

Solution 1: Access the variables through the class

class Electronicdevice:
    Devices = 100


class Pocketgadgets(Electronicdevice):
    Pocketdevices = 40


class Phone(Pocketgadgets):
    Phones = Electronicdevice.Devices - Pocketgadgets.Pocketdevices


Samsung = Electronicdevice()
Galaxy = Pocketgadgets()
SamsungGalaxyS21 = Phone()

print(SamsungGalaxyS21.Phones)
60

NB: this example is independent of the inheritance, that is, even if you don't inherit from **Pocketgadgets** class, it will still work.

Solution 2: Access the variables through an instance of the class

class Electronicdevice:
    Devices = 100


class Pocketgadgets(Electronicdevice):
    Pocketdevices = 40


class Phone(Pocketgadgets):

    def __init__(self):
        self.Phones = self.Devices - self.Pocketdevices


Samsung = Electronicdevice()
Galaxy = Pocketgadgets()
SamsungGalaxyS21 = Phone()

print(SamsungGalaxyS21.Phones)
60
  • Related