我有以下代码:
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
我想得到以下信息:
My Computer, Intel
但我收到以下错误:
AttributeError: 'Computer' object has no attribute 'CPU'
如何正确设置类,以便在运行主要代码后,我会得到我需要的东西?我什至不确定我是否完全正确地使用了 super() 。
非常感谢您的帮助。
最佳答案
您构建的层次结构中的语义问题是 CPU
其实不是电脑类型,是part
的计算机,因此您应该将其定义为 attribute
而不是子类型:
class Computer(object):
def __init__(self, name, cpu):
self.name = name
self.cpu = cpu
层次相关的类应该有一些共同点,即使它们代表不同的事物并且具有帮助我们识别它们的独特属性。例如;汽车是车辆,卡车也是车辆,因此车辆可以定义为汽车和卡车的父类(super class)。虽然它们看起来完全不同,但它们与车辆有一些共同点:发动机、车轮、变速箱等。
回到你的问题,CPU 基本上是计算机的心脏,所有类型计算机的必需品 所以它应该是从父类(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')
有个好read关于Python中的类继承。我强烈建议您阅读一次。
关于Python - 如何正确设置类的层次结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31899465/