我是一名初学 Python 的编码员,我正在尝试创建一个能够与程序的其他部分(例如 def 语句)交互的简单属性系统。基于我目前对 Python 语言的微薄了解,我假设完成此任务的最佳方法是使用类和 def 语句来创建与相关类相关的命令和操作。每当我尝试运行我的代码时,我都会遇到这个错误:
if petname['hungry'] == True:
TypeError: 'type' object is not subscriptable
同样,我现在的知识非常有限,所以我不知道我的程序是否接近可用,或者它是否只是无用的垃圾。我会在这里发布我的代码。我将不胜感激一些纠正性的批评;或者,见鬼,如果有人能为我正确地重写它,那就太好了!
这是我写的代码。让我知道是否需要更多信息才能给出全面的答案:
petname = 'Dog'
class petname (object):
attributes = {'health': 20, 'attack': 4, 'size': 5, 'hunger': True}
def feed(petname):
if petname['hungry'] == True:
petname['hungry'] = False
petname['size'] = petname['size'] + 1
print("{0} happily gobbles down the treat!".format(petname))
else:
print("{0} is not hungry.".format(petname))
if petname['hungry'] == True:
print("{0} is hungry! Feed it something!".format(petname))
input()
请您参考如下方法:
您正在重复使用名称 petname跨你的代码,并期望它即使在相同的上下文中也有不同的含义。你的petname class 没有多大意义,因为单个 pername.attributes字典将在所有 petname 的实例之间共享对象。
下面,我整理了Pet对象具有属性,使用继承为狗建立默认值,并使 feed Pet 的一种方法类:
class Pet(object):
def __init__(self, name, health, attack, size, hunger):
self.name = name
self.health = health
self.attack = attack
self.size = size
self.hunger = hunger
def feed(self):
if self.hunger:
self.hunger = False
self.size += 1
print("{0} happily gobbles down the treat!".format(self.name))
else:
print("{0} is not hungry.".format(petname))
class Dog(Pet):
def __init__(self, name):
super(Dog, self).__init__(name, 20, 4, 5, True)
spot = Dog("Spot")
spot.feed()
# Spot happily gobbles down the treat!
