我想用Python(类和DEF语句)创建一个基本属性系统



我是一个从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类并没有多大意义,因为单个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!

相关内容

最新更新