Python 当前实例的静态变量
Python static variable of current instance
我想要一个静态可用的 class 实例。下面是一个例子:
class Car:
ford = Car(brand='Ford')
mercedes = Car(brand='Mercedes')
bmw = Car(brand='BMW')
def __init__(self, brand: str):
self.brand = brand
例如,这将允许我执行 Car.ford
。但是,它说 class Car
不存在。这在 Python 中可行吗?
我看过其他 post 解释静态变量如何与 classes 和实例相关,但我无法找到 post 关于实例的静态变量同样 class。所以下面的例子不是我的意思:
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 实例的静态变量。
你可以这样做
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')
我想要一个静态可用的 class 实例。下面是一个例子:
class Car:
ford = Car(brand='Ford')
mercedes = Car(brand='Mercedes')
bmw = Car(brand='BMW')
def __init__(self, brand: str):
self.brand = brand
例如,这将允许我执行 Car.ford
。但是,它说 class Car
不存在。这在 Python 中可行吗?
我看过其他 post 解释静态变量如何与 classes 和实例相关,但我无法找到 post 关于实例的静态变量同样 class。所以下面的例子不是我的意思:
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 实例的静态变量。
你可以这样做
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')