我是Python新手,我正在学习类和函数,我想打印一个类的函数,但我得到的只是错误"Class没有属性“
items.py:
class Item():
def __init___(self, name, desc, val):
self.name = name
self.desc = desc
self.val = val
def print_info(self):
return '{}\n==========\n{}\n\nValue: {}'.format(self.name, self.desc, self.val)
class Gold(Item):
def __init__(self):
super().__init__(name = "Gold", desc = "Golden coin.", val = str(5))main.py:
from items import Item
print(Item.Gold.print_info)错误是
"AttributeError: type object 'Item' has no attribute 'Gold'"发布于 2015-02-11 18:36:19
Gold不是Item类的属性,不是。它本身就是一个子类,也是一个全局名称。您可以从您的items模块导入它:
>>> from items import Gold
>>> Gold
<class 'items.Gold'>您不能创建它的实例,因为对Item.__init__方法使用了错误的名称:
>>> from items import Item
>>> Item.__init__
<slot wrapper '__init__' of 'object' objects>
>>> Item.__init___
<function Item.__init___ at 0x1067be510>
>>> Item('a', 'b', 4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object() takes no parameters请注意,您创建的方法的名称中有三个下划线。如果你修好了:
class Item():
def __init__(self, name, desc, val):
# ^ ^ 2 underscores on both sides
self.name = name
self.desc = desc
self.val = val您可以创建Gold()类的实例:
>>> Gold()
<items.Gold object at 0x1067cfb00>
>>> gold = Gold()
>>> print(gold.print_info())
Gold
==========
Golden coin.
Value: 5现在,如果您真的想在Item类上创建属性,那么您必须在创建该类之后添加这些属性:
class Item():
def __init___(self, name, desc, val):
self.name = name
self.desc = desc
self.val = val
def print_info(self):
return '{}\n==========\n{}\n\nValue: {}'.format(self.name, self.desc, self.val)
Item.gold = Item('Gold', 'Golden coin.', 5)您不需要为此创建子类。不过,您可以在这里使用 module:
from enum import Enum
class Item(Enum):
Gold = 'Golden coin.', 5
Silver = 'Silver coin.', 1
def __init__(self, desc, val):
self.desc = desc
self.val = val
def print_info(self):
return '{}\n==========\n{}\n\nValue: {}'.format(self.name, self.desc, self.val)这里Gold是Item的一个属性
>>> Item
<enum 'Item'>
>>> Item.Gold
<Item.Gold: ('Golden coin.', 5)>
>>> print(Item.Gold.print_info())
Gold
==========
Golden coin.
Value: 5
>>> Item.Silver
<Item.Silver: ('Silver coin.', 1)>发布于 2015-02-11 18:39:50
以下是你做错的事:
Gold是Item的子类,而不是它的一个属性。当您尝试执行Item.Gold时,会出现错误。黄金是完全分开获取的。super()。Item类的__init__()中有一个额外的下划线因此,考虑到这一点,您的新main.py应该如下所示:
from items import Gold
mygold = Gold() # This is where we instantiate Gold into an object
print(mygold.print_info()) # We call the method on the object itself你的items.py会是这样的:
class Item():
def __init__(self, name, desc, val):
self.name = name
self.desc = desc
self.val = val
def print_info(self):
return '{}\n==========\n{}\n\nValue: {}'.format(self.name, self.desc, self.val)
class Gold(Item):
def __init__(self):
Item.__init__(name = "Gold", desc = "Golden coin.", val = str(5))https://stackoverflow.com/questions/28461632
复制相似问题