无法访问类变量进行打印,因为它是NoneType对象

时间:2017-03-05 00:24:54

标签: python python-3.x class

我有一个类如:

class MP3:
    name = ""
    capacity = 0
    def newMP3(name, capacity):
        MP3.name = name
        MP3.capacity = capacity

我的主要剧本:

from mp3class import *
currentMP3 = MP3.newMP3("myName", 10)
print (currentMP3.name)
print (currentMP3.capacity)

但是,print语句会返回错误:

AttributeError: 'NoneType' object has no attribute 'name'

我刚刚分配时为什么currentMP3 == None

我在return (name, capacity)的末尾尝试了class MP3,这给了我一个不同的错误:

AttributeError: 'tuple' object has no attribute 'name'

即使元组中有name吗?

2 个答案:

答案 0 :(得分:3)

您在致电后隐式退回None

def newMP3(name, capacity):
    MP3.name = name
    MP3.capacity = capacity

并将其分配给名称currentMP3

您正在寻找__init__来初始化具有某些属性的新实例:

def __init__(self, name, capacity):
    self.name = name
    self.capacity = capacity

或者,作为替代方案,您可以直接更改类属性,然后使用@classmethod创建新实例:

@classmethod
def newMP3(cls, name, capacity):
    cls.name = name
    cls.capacity = capacity
    return cls()

答案 1 :(得分:0)

您班级中的newMP3方法不会返回任何内容。在Python中,这与返回None相同。因此,当您执行currentMP3 = MP3.newMP3(...)时,currentMP3变为None,并且无法访问您在MP3类上设置的类属性。

请注意,使用类属性而不使用实例非常奇怪。如果你继续走这条路,我会期待很多其他的错误。更自然的实现将创建MP3类的实例并在实例上设置属性。