23

我有以下课程:

class vehicle(object):
    def __init__(self, name):
        self.name = name
        self.kinds_list = ["tank", "car", "motorbike", "bike", "quad" ] 

    @property
    def kind(self):
        return self.kind

    @kind.setter
    def kind(self, x):
        if x in self.kinds_list:
            self.kind = x
        else:
            raise AttributeError('No attribute {0} found !'.format(y))

设置 kind 会导致超出最大递归深度,也就是堆栈溢出。

问:如何重新编写 setter 使其仅适用于固定列表?

4

1 回答 1

35

The reason you reached the maximum recursion depth is that inside your setter, you do self.kind = ..., which recursively calls the same setter. You should store the value as some private attribute, just rename self.kind to self._kind.

class vehicle(object):
    def __init__(self, name):
        self.name = name
        self.kinds_list = ["tank", "car", "motorbike", "bike", "quad" ] 

    @property
    def kind(self):
        return self._kind

    @kind.setter
    def kind(self, x):
        if x in self.kinds_list:
            self._kind = x
        else:
            raise ValueError('{0} is an illegal kind of vehicle!'.format(y))

This is not a real private attribute like in other languages, since nothing prevents you from accessing my_vehicle._kind. By convention in python, everything starting with an underscore is private and shouldn't normally be touched outside of the class. Or as they say: python is for consenting adults ;).

I also slightly modified the error message in the setter.

于 2013-09-24T18:35:01.713 回答