内部类内部的外部方法



假设我有三个类:汽车(外部(、发动机(内部(和制动器(另一个内部(。我永远不会在任何情况下使用发动机或刹车,我还没有使用汽车。

此外,Car的工作繁重(比如读取一个大的CSV文件(。我只想在代码中调用它一次,然后用Engine和Brake处理这些数据。

最后,我知道我会在Engine或Brake中使用一个函数,所以我想我应该在Car中创建它,然后从Car中生成Engine和Brake子类。

我的代码:

class Car:
def __init__(self,foo,bar):
self.foo = foo
self.bar = bar

def some_method(self):
print('im outer but used inner')

class Engine():
def __init__(self):
self.some_method()

class Brake():
def __init__(self):
self.some_method()

如果我运行:

test = Car('a','b')
test.Engine()

我得到了:

AttributeError: 'Engine' object has no attribute 'some_method'

我的错误在哪里?

首先,汽车不是发动机,但汽车有发动机,所以你需要做"组合物";,它正在Engine类中创建Car的对象(Brake类也是如此(,示例代码:

class Car:
def __init__(self,foo,bar):
self.foo = foo
self.bar = bar

def some_method(self):
print('im outer but used inner')
class Engine:
def __init__(self):
self.car=Car() #here i created an object of car inside of Engine class
def get_method(self):
self.car.some_method()

组成的定义:组成是一个概念,模型有一种关系。它允许通过组合其他类型的对象来创建复杂的类型。这意味着类Composite可以包含另一个类Component的对象。这种关系意味着组合具有一个组件。->来源:https://realpython.com/inheritance-composition-python/#:~:text=合成%20is%20a%20concept%20hat,a%20Composite%20has%20a+20Component%20。

现实生活中的例子:在现实生活中,复杂的对象通常是由更小、更简单的对象构建的。例如,汽车是用金属框架、发动机、一些轮胎、变速器、方向盘和大量其他零件制造的。个人电脑是由CPU、主板、一些内存等组成的……即使你是由较小的部分组成的:你有头、身体、腿、手臂等等

最新更新