我想让一个类的实例静态可用。下面的例子:
class Car:
ford = Car(brand='Ford')
mercedes = Car(brand='Mercedes')
bmw = Car(brand='BMW')
def __init__(self, brand: str):
self.brand = brand
例如,这将允许我执行Car.ford
。但是,它说类别Car
不存在。这在Python中可行吗?
我看过其他文章,解释了静态变量与类和实例之间的关系,但是我找不到关于同一类实例的静态变量的文章。所以下面的例子不是我的意思:
class Car:
wheels = 4
def __init__(self, brand: str):
self.brand = brand
Car.wheels # Will give me 4
trike = Car(brand='Trike')
trike.wheels # Will give me 4
trike.wheels = 3
trike.wheels # Will give me 3
Car.wheels # Still gives me 4
我谈论的是该类实例的静态变量。
class Car:
def __init__(self, brand: str):
self.brand = brand
Car.ford = Car(brand='Ford')
Car.mercedes = Car(brand='Mercedes')
Car.bmw = Car(brand='BMW')