Python 无法访问类变量进行打印,因为它是非类型对象
我有一门课,比如:Python 无法访问类变量进行打印,因为它是非类型对象,python,python-3.x,class,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 (currentMP
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'
我刚刚分配了currentm3==None
为什么
我在MP3类的末尾尝试了返回(名称、容量)
,这给了我一个不同的错误:
AttributeError: 'tuple' object has no attribute 'name'
即使元组中确实有
名称
?调用后,您将隐式返回无
:
def newMP3(name, capacity):
MP3.name = name
MP3.capacity = capacity
并将其分配给名称currentMP3
您正在寻找\uuuu init\uuuu
以使用某些属性初始化新实例:
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()
调用以下命令后,您将隐式返回
None
:
def newMP3(name, capacity):
MP3.name = name
MP3.capacity = capacity
并将其分配给名称currentMP3
您正在寻找\uuuu init\uuuu
以使用某些属性初始化新实例:
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()
类中的
newMP3
方法不会返回任何内容。在Python中,这与返回None
相同。因此,如果执行currentm3=MP3.newMP3(…)
,currentm3
将变为None
,并且无法访问在MP3
类上设置的类属性
请注意,使用类属性而不使用实例是非常奇怪的。如果你继续走那条路,我会看到很多其他的虫子。更自然的实现是创建
MP3
类的实例并设置实例的属性。类中的newMP3
方法不会返回任何内容。在Python中,这与返回None
相同。因此,如果执行currentm3=MP3.newMP3(…)
,currentm3
将变为None
,并且无法访问在MP3
类上设置的类属性
请注意,使用类属性而不使用实例是非常奇怪的。如果你继续走那条路,我会看到很多其他的虫子。更自然的实现是创建MP3
类的实例,并在实例上设置属性