当前实例的Python静态变量

问题描述 投票:0回答:1

我想让一个类的实例静态可用。下面的例子:

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

我谈论的是该类实例的静态变量。

python-3.x variables inheritance static instance
1个回答
2
投票
您可以这样操作

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')

© www.soinside.com 2019 - 2024. All rights reserved.