python - 是否可以在 python 中进行两种方式的组合?

标签 python python-3.x class composition

首先,如果以错误的方式提出这个问题,我深表歉意,所以请不要欺骗我。我正在尝试做的是与以下内容非常相似的事情。

class Driver:
    def __init__(self):
        self.kind = "Driver"
    def class_of_driver(self):
        if self.model == 'corvette':
            print('fast')
class Car:
    def __init__(self, brand, model, cost, color):
        self.brand = brand
        self.model = model
        self.cost = cost
        self.color = color
        self.drivers = Driver()

我希望能够像这样创建对象:

corvette = Car('chevy','corvette','200','red')

然后最终能够做类似的事情:

corvette.class_of_driver

corvette.class_of_driver()

并在这种情况下获得快速的返回。我已经搞砸了一个小时左右,然后陷入困境。我知道我可以像这样将自己传递给自己:

self.drivers = Driver(self)

当然,如果对象在未来发生变化,它不会反射(reflect)这种变化。

如有任何建议,我将不胜感激,在此先表示感谢。

最佳答案

当然可以。两个对象互相引用是很常见的。这是一种方法:

class Driver:
    def __init__(self, car):
        self.kind = "Driver"
        self.car = car
    def class_of_driver(self):
        if self.car.model == 'corvette':
            print('fast')
class Car:
    def __init__(self, brand, model, cost, color):
        self.brand = brand
        self.model = model
        self.cost = cost
        self.color = color
        self.driver = Driver(self)

    def class_of_driver(self):
        return self.driver.class_of_driver()


corvette = Car('chevy','corvette','200','red')

corvette.class_of_driver()

关于python - 是否可以在 python 中进行两种方式的组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43664255/

相关文章:

python - 如何删除 Google OR-Tools CVRP 中的最后一条路径(return-back-to-depot)?

python - 为什么我从 GUI Python 教科书中获取的这段代码有效?

python - 从执行存储过程的 psycopg2 游标获取列名列表?

regex - 查找最里面的大括号中以给定子字符串的单词开头的文本

java - 当两个对象相同时,为什么 equals() 方法返回 false?

类对象数组中的 C++ 内存

python - 返回按下的键的名称

python - 递归树生成器中的无限递归

python - 计算机之间的套接字

html - 带有类的图形标签中的 img 标签不起作用