【问题标题】:How to get ever-changing Python property [closed]如何获得不断变化的 Python 属性
【发布时间】:2019-06-29 13:06:59
【问题描述】:

这没有帮助,https://docs.python.org/3/library/functions.html#property

如何获取对象的属性?

我试过了

msg=property(thing.desc())

msg=property(thing.desc(noun))

我错过了什么.....

下面是代码

import sys

class GameObject:
    class_name=""
    desc=""
    objects={}

    def __init__(self,name):
        self.name=name
        GameObject.objects[self.class_name]=self

    def get_desc(self):
        return self.class_name+"\n"+self.desc



class Goblin(GameObject):

    def __init__(self,name):
        self.class_name="goblin"
        self.health=3
        self.desc="A foul creature"
        super().__init__(name)

    @property
    def desc(self):
        if self.health>=3:
            return self._desc
        elif self.health==2:
            health_line="It has a wound on its knee."
        elif self.health==1:
            health_line="Its left arm has been cut off!"
        elif self.health<=0:
            health_line="It is dead."
        return self._desc+"\n"+health_line

    @desc.setter
    def desc(self,value):
        self._desc=value


goblin = Goblin("Gobbly")

def get_input():
        command=input(":").split()
        verb_word=command[0]
        if verb_word in verb_dict:
            verb=verb_dict[verb_word]
        else:
            print("Unknown verb {}".format(verb_word))
            return

        if len(command) >= 2:
            noun_word = command[1]
            print (verb(noun_word))
        else:
            print(verb("nothing"))  

def say(noun):
    return 'You said "{}"'.format(noun)

def examine(noun):
    if noun in GameObject.objects:
        return GameObject.objects[noun].get_desc()
    else:
        return "There is no {} here.".format(noun)

def hit(noun):
    if noun in GameObject.objects:
        thing=GameObject.objects[noun]
        if type(thing)==Goblin:
            thing.health=thing.health-1
            if thing.health<=0:
                msg="You killed the goblin!"
            else:
                msg=property(thing.desc(noun))
        else:
            msg="There is no {} here".format(noun)
        return msg


def exit(noun):
    sys.exit(0)

verb_dict = {
    "say": say,
    "examine": examine,
    "hit": hit,
    "exit": exit,
}
while True:
    get_input()

【问题讨论】:

  • 您创建了一个属性,因此只需访问名称作为属性thing.desc.
  • 不是函数,不能调用。访问实例上的名称时解析属性。

标签: python properties


【解决方案1】:

将行改为简单:

msg = thing.desc

【讨论】:

    猜你喜欢
    • 2019-09-23
    • 2012-11-12
    • 1970-01-01
    • 2020-03-08
    • 1970-01-01
    • 1970-01-01
    • 2016-05-09
    • 1970-01-01
    • 2016-08-31
    相关资源
    最近更新 更多