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

nia*_*son 4 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
Run Code Online (Sandbox Code Playgroud)

我想得到以下内容:

My Computer, Intel
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误:

AttributeError: 'Computer' object has no attribute 'CPU'    
Run Code Online (Sandbox Code Playgroud)

如何正确设置类,所以一旦我运行主代码,我会得到我需要的东西?我甚至不确定我是否正确使用super().

我非常感谢你的帮助.

ozg*_*gur 6

您构建的层次结构中的语义问题CPU实际上不是计算机类型,而是计算机类型part,因此您应该将其定义为attribute而不是子类型:

class Computer(object):
    def __init__(self, name, cpu):
        self.name = name
        self.cpu = cpu
Run Code Online (Sandbox Code Playgroud)

层次相关的类应具有共同点,即使它们代表不同的东西并具有帮助我们识别它们的唯一属性.例如; 汽车是一种车辆,卡车也是一种车辆,因此汽车可以被定义为汽车和卡车的超级汽车.虽然它们看起来完全不同,但它们有一些共同的东西:发动机,车轮,传动装置等.

回到你的问题,CPU基本上是计算机的核心,是所有类型计算机的必需品,所以它应该是从超类继承的东西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
Run Code Online (Sandbox Code Playgroud)
>>> macbook = Laptop('My Macbook', 'Intel', 'Apple')
>>> atm = AutomatedTellerMachine('ATM 1', 'AMD', 'Wells Fargo')
Run Code Online (Sandbox Code Playgroud)

在Python中有关于类继承的很好的阅读.我强烈建议你阅读一次.


Cyp*_*ase 3

我认为你根本不需要子类化。

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)
Run Code Online (Sandbox Code Playgroud)

给出这个输出:

My Computer, Intel
Run Code Online (Sandbox Code Playgroud)

  • 您应该传递“cpu”本身,而不是将“cpu_manufacturer”传递给“Computer”。`my_computer = 计算机('我的电脑', CPU('英特尔'))` (3认同)