2

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

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

我可以使用 getter 编写此函数吗?我是否必须求助于制作自己的 get_max_velocity() 函数(或直接变量访问)?

4

0 回答 0