Python - 列表中的属性设置导致超出最大递归深度 [英] Python - Property setting from list causes maximum recursion depth exceeded

查看:45
本文介绍了Python - 列表中的属性设置导致超出最大递归深度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

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

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

Setting kind causes the maximum recursion depth exceeded aka stack overflow.

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

Q: How to re-write the setter to make it work with fixed list only?

推荐答案

你达到最大递归深度的原因是在你的 setter 中,你做了 self.kind = ...,它递归地调用相同的 setter.您应该将该值存储为一些私有属性,只需将 self.kind 重命名为 self._kind.

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

这不像在其他语言中那样是真正的私有属性,因为没有什么可以阻止您访问 my_vehicle._kind.按照 Python 的惯例,以下划线开头的所有内容都是私有的,通常不应在类之外触及.或者 正如他们所说:python 是为了成年人的同意;).

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 ;).

我也稍微修改了 setter 中的错误信息.

I also slightly modified the error message in the setter.

这篇关于Python - 列表中的属性设置导致超出最大递归深度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆