静态类变量的Python getter / setter

时间:2019-11-22 07:24:54

标签: python-3.8

我目前有一些代码,例如:

class Bird:
    pass

class Swallow(Bird):
    __max_airspeed_velocity = 10

    def __init__(self, laden):
        self.laden = laden

    @property
    def max_velocity(self):
        return self.__max_airspeed_velocity

    @property
    def current_velocity(self):
        if self.laden:
            return self.__max_airspeed_velocity / 2
        else:
            return self.__max_airspeed_velocity

class Parrot(Bird):
    __max_in_cage_velocity = 8

    def __init__(self, dead):
        self.dead = dead

    @property
    def max_velocity(self):
        return self.__max_in_cage_velocity

    @property
    def current_velocity(self):
        if self.dead:
            return 0
        else:
            return self.__max_in_cage_velocity


swallow = Swallow(True)
parrot = Parrot(False)

# Direct variable access is fine
swallow.__max_airspeed_velocity  # 10
Swallow.__max_airspeed_velocity  # 10

# Getter only works on instance. I see that it references "self", but it only looks at a class variable.
# In practice, this is an obvious reason why it doesn't work. But in theory there should still be a way?
swallow.max_velocity # 10
Swallow.max_velocity # Error

现在让我们说我想要一个比较鸟类的函数。我有时想问一下理论上的鸟类(班级),有时甚至是实际的鸟类(实例)。

def compare_max_velocity(bird1, bird2):
    return bird1.max_velocity > bird2.max_velocity  # only works on instances

compare_max_velocity(Swallow, Parrot)  # can I do this using built-ins?
compare_max_velocity(swallow, parrot)  # easy

我可以使用吸气剂编写此功能吗?我是否必须借助自己的get_max_velocity()函数(或直接变量访问)?

0 个答案:

没有答案