Python - 如何正确设置类的层次结构?

标签 python class subclass super

我有以下代码:

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/

相关文章:

java - 单例模式中枚举相对于类的优势

java - 为什么子类必须先调用父类(super class)的构造函数才能初始化自己的变量

JavaScript 原型(prototype)设计 : single prototype object or not?

python - 在 Pandas 中查询 HDF5

java - Android - 检查我来自哪个类(class)

Python类实例在新线程中启动方法

python - 类型提示中的子类

python - 交叉两个字典

Python 等效于 R apply with anonymous function

python - 由于 Python 中的 ascii 错误,将数据写入 CSV 时出错