gpt4 book ai didi

python - 不将任何内容传递给属性会导致崩溃

转载 作者:行者123 更新时间:2023-12-01 05:21:15 26 4
gpt4 key购买 nike

我使用属性来获取/设置类中的变量,但是当变量设置为 None 时,程序会在下次设置变量时崩溃 - 如以下代码所示:

class Abc(object):
def __init__(self, a=None):
self.a = a

def set_a(self, value):
self._a = value*5

def get_a(self):
return self._a

a = property(get_a, set_a)

A = Abc()
A.a = 4
print A.a

当我运行这个时,我得到:

Traceback (most recent call last):
File "<string>", line 13, in <module>
File "<string>", line 3, in __init__
File "<string>", line 6, in set_a
TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'

编写代码以阻止此错误发生的正确方法是什么?

最佳答案

设置self._a,而不是self.a;后者使用属性 setter :

class Abc(object):
def __init__(self, a=None):
self._a = a

或使用数字默认值:

class Abc(object):
def __init__(self, a=0):
self.a = a

关于python - 不将任何内容传递给属性会导致崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22298981/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com