【问题标题】:Reassigning self attribute and getting AttributeError重新分配 self 属性并获取 AttributeError
【发布时间】:2020-06-23 02:53:27
【问题描述】:

这是我的代码:

class BasicPlan(object):
    
    def __init__(self, can_stream, can_download, has_SD, has_HD, has_UHD, num_of_devices, price):
        self.can_stream = can_stream
        self.can_download = can_download
        self.has_SD = has_SD
        self.has_HD = has_HD
        self.has_UHD = has_UHD
        self.num_of_devices = num_of_devices
        self.price = price

    def default(self):
        self.can_stream = True
        self.can_download = True
        self.has_SD = True
        self.has_HD = False
        self.has_UHD = False
        self.num_of_devices = 1
        self.price = "$8.99"

在python shell中,我创建一个对象如下:

test = BasicPlan('randomValue', 'randomValue', 'randomValue', 'randomValue', 'randomValue', 'randomValue', 'randomValue')

然后我尝试应用默认方法,以便重新分配 self 值:

test = test.default()

现在我尝试打印一个属性:

print(test.can_stream)

我得到:

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    print(test.can_stream)
AttributeError: 'NoneType' object has no attribute 'can_stream'

【问题讨论】:

  • test.default() 返回None。分配后test 变为None。删除test =

标签: python class attributeerror self


【解决方案1】:

我想我会把我的评论作为正式的回答,因为我有额外的建议。

首先,test.default() 返回None。分配后test 变为None。删除test =

其次,可以给构造函数提供默认值,就不需要单独的default()方法了:

def __init__(self, can_stream=True, can_download=True, has_SD=True, has_HD=False, has_UHD=False, num_of_devices=1, price="$8.99"):
    self.can_stream = can_stream
    self.can_download = can_download
    self.has_SD = has_SD
    self.has_HD = has_HD
    self.has_UHD = has_UHD
    self.num_of_devices = num_of_devices
    self.price = price

test = BasicPlan() # An object is created with the default values

最后,不要将价格存储为字符串。将其存储为整数美分。

【讨论】:

    猜你喜欢
    • 2020-12-03
    • 1970-01-01
    • 2020-04-21
    • 2022-07-17
    • 2019-09-17
    • 1970-01-01
    • 2012-10-17
    • 2021-08-04
    • 1970-01-01
    相关资源
    最近更新 更多