I have the following code:
class Computer(object):
def __init__(self, name):
self.name = name
class CPU(Computer):
def __init__(self):
super(CPU, self).__init__(name)
self.name = name
mycomputer = Computer('My Computer')
mycomputer.CPU.name = 'Intel'
print mycomputer.name, mycomputer.CPU.name
I would like to get the following:
My Computer, Intel
But I'm getting the following error:
AttributeError: 'Computer' object has no attribute 'CPU'
How do I set up the class correctly, so once I run the main code, I would get what I need? I'm not even sure if I'm using super() correctly at all.
I really appreciate all your help.
The semantical problem in the hierarchy you built is the fact that CPU
is actually not a computer type, it is a part
of computer, so you should have defined it as an attribute
instead of a sub type:
class Computer(object):
def __init__(self, name, cpu):
self.name = name
self.cpu = cpu
Classes that are hierarchically related should have something in common even if they represent different things and have unique attributes that help us identify them. For instance; a car is a vehicle, a truck is also a vehicle so that vehicle can be defined as super class of both car and truck. Although they look totally different, they have something in common as vehicles: engine, wheel, transmission etc.
Getting back to you question, a CPU is basically a heart of computer, a required thing for all type of computers so it should be something that is inherited from super class Computer
:
class Computer(object):
def __init__(self, name, cpu):
self.name = name
self.cpu = cpu
class Laptop(Computer):
def __init__(self, name, cpu, manufacturer):
super(Laptop, self).__init__(name, cpu)
self.manufacturer = manufacturer
class AutomatedTellerMachine(Computer):
def __init__(self, name, cpu, bank):
super(AutomatedTellerMachine, self).__init__(name, cpu)
self.bank = bank
>>> macbook = Laptop('My Macbook', 'Intel', 'Apple')
>>> atm = AutomatedTellerMachine('ATM 1', 'AMD', 'Wells Fargo')
There is a good read about class inheritance in Python. I'd strongly recommend to read it once.
I don't think you want subclassing at all.
class Computer(object):
def __init__(self, name, cpu):
self.name = name
self.cpu = cpu
class CPU(object):
def __init__(self, manufacturer):
self.manufacturer = manufacturer
intel_cpu = CPU('Intel')
mycomputer = Computer('My Computer', intel_cpu)
print "{}, {}".format(mycomputer.name, mycomputer.cpu.manufacturer)
Gives this output:
My Computer, Intel
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With