简体   繁体   English

你如何调用 class 的属性,就好像它是一个变量(在 python 中)?

[英]How do you call on an attribute of a class, as if its a variable (in python)?

Im new to coding, and pretty confused by the concept of class 's and how to use them.我是编码新手,对 class 的概念以及如何使用它们感到非常困惑。 Im making a zork game as a practice exercise and have the following as part of my code:我制作了一个 zork 游戏作为练习,并将以下内容作为我的代码的一部分:

def buildCharacter():
    return(Hero(input("What is your name, traveler? \n> "))) 

class Hero(object): #creates class Hero, Hero has-a name and has-a health
    def __init__(self, name, health=10):
        self.name = name
        self.health = health

Later in the code, if the player gets 'hurt' I want to be able to reduce health, until its 0 and they 'die'.稍后在代码中,如果玩家“受伤”,我希望能够减少生命值,直到它为 0 并且他们“死亡”。 I tried doing:我试着做:

self.health -= 5
if self.health <=0:
      exit(0)

but that doesn't work, saying 'self' not defined.但这不起作用,说“自我”没有定义。 How do I call on self.health to change it?我如何调用 self.health 来改变它?

Edit: Ive been told that the whole code should be posted, so here it is:编辑:我被告知应该发布整个代码,所以这里是:

from sys import exit
import time #Lets you pause the command window for a sec

have_sword = False
gate_unlocked = False

class Hero(object): #creates class Hero, Hero has-a name and has-a health
    def __init__(self, name, health=10):
        self.name = name
        self.health = health

    def take_dammage(self, dammage):
        self.health -= dammage

    def getHealth(self):
        return self.health

#first room: sphynx with riddle, door with password
def sphynx():
    print("You enter a room with a sphynx and a door.")

    while True: #create infinite loop to begin again if password unknown
        print("What do you do?")
        choice = input("\n1) Fight the sphynx \n2) Speak to the sphynx \n3) try the door \n>")
        if "attack" in choice or "fight" in choice or "1" in choice:
                MyName.health -= 5
                print(f"You can't beat a sphynx unarmed! \nHealth is now {MyName.health}")
                if MyName.health <= 0:
                    dead()
        elif "speak" in choice or "talk" in choice or "ask" in choice or "question" in choice or "2" in choice:
            print("""The sphynx is board, instead of telling you the password easily, it asks you a riddle:
            'First think of the person who lives in disguise,
            who deals in secrets and tells only lies.
            Next, tell me what's always the last thing to mend,
            the middle of middle and the end of end?
            Fianally, give me a sound often heard
            durring the search for a hard to find word.
            Now string them together, and answer me this,
            what creature would you be unwilling to kiss?'

            OK, but how is that going to help you??
            """); time.sleep(1)
        elif "door" in choice or "open" in choice or "try" in choice or "3" in choice:
            print("What's the password?")
            password = input("> ")
            if password == "spider":
                print("Correct! You go through the open door")
                room2()
            else: #starts while loop ovewr again
                print("Nope. \nTry again. \nMaybe the sphynx knows...")
                continue
        else: #starts while loop ovewr again
            print("naw mate, try again")

def room2():
    print("You enter a room with a red door and a blue door.")
    global have_sword

    while True: #create infinite loop to begin again if door not chosen
        choice = input("Which do you enter?\n>")

        if "red" in choice:
            print("You enter a pitch black room. What do you do?")
            darkChoice = input("\n1) Feel for a light swith \n2) Turn around and leave \n3) \"the dark doesn's scare me, I venture forward into the gloom\" \n> ")
            while True: #create infinite loop to begin again if no option chosen
                if "feel" in darkChoice or "light" in darkChoice or "1" in darkChoice:
                    print("You find a light switch and turn it on. \nIn the room, you see a small box and a large one.")

                    while True: #create infinite loop to begin again if no option chosen
                        print("Which box do you open?")
                        boxChoice = input("> ")
                        if "small" in boxChoice or "little" in boxChoice:
                            print("you open the small box to find a wormhole. \nIt sucks you in and you find yourself BACK in the second room.")
                            room2()
                        elif "big" in boxChoice or "large" in boxChoice:
                            print("You find a sword. \nStow it for later use. \nFor now, go back to the second room")
                            have_sword = True
                            room2()
                        else: #starts while loop over again
                            print("You gotta pick one.")
                else:
                    dead("you get lost in the darkness and starve.")
        elif "b" in choice:
            oldShack()
        else: #starts while loop ovewr again
            print("naw mate, try again")

def oldShack():
    print("You enter and old, rickety shack. \nThe paint is peeling, the floorboards sticking up, and ceiling caving in. \nThere's a rusty gate at the back.")
    global gate_unlocked

    while True: #create infinite loop to begin again if no option chosen
        print("What do you do in the shack? ")
        choice = input("1) Search under the floorboards \n2) Try the gate \n3) Go back \n> ")

        if "check" in choice or "floor" in choice or "board" in choice or "1" in choice:
            print("You find a key under the floorboards!")
            gate_unlocked = True
        elif "door" in choice or "gate" in choice or "2" in choice and gate_unlocked == True:
            print("You use the key you found, it works!")
            cave()
        elif "Push really hard" in choice:
            print("Damn, you're really strong!")
            cave()
        elif "door" in choice or "gate" in choice or "2" in choice and gate_unlocked != True:
            print("the gate is locked.")
        elif "3" in choice or "back" in choice:
            room2()
        else:
            print("naw mate, try again")

def cave():
    print("You find yourself in a cave that is home to a collosal, sleeping red dragon. ")
    global have_sword

    while True:
        choice = input("How do you deal with the dragon? \n1) Attack with your sword \n2) Attack unarmed \n3) Speak to the dragon \n4) Run before the dragon wakes \n>")

        if "1" in choice and have_sword == True:
            print("A mighty battle ensures. \n Using your sword, you slay the dragon \nBefore you stands a great pile of generations of dragon treasure; gold and juels and riches beyond your wildest dreams. \nAt the end of the cave lies a small brown chest. \nDo you: \n1) Take the treasure \n2) Open the box")
            rich = input("> ")
            while True:
                if "1" in rich or "gold" in rich:
                    dead("A deep voice echos from the depths of the cave: \n'Greed is the downfall of man.' \nThe cave rumbles and collaples around you.")
                elif "2" in rich or "box" in rich or "brown" in rich:
                    print("You open the box to find the deep crimson Dream Stone. \nYou have succesded in your quest, 1) this could save King Arthurs kingdom from *vague, unspecified threat* \nOr... \n2) Or you could sell if and buy a kingdom of you very own!")
                    success = input("> ")
                    if "1" in success:
                        win("You successfully passed all the chalanges!\n")
                    else:
                        dead("You walk out of the cave, daydreaming about what life will be like as a king \nWhile you are distracted by your thoughts, you trip over the dead dragons tail and hit your head")
                else:
                    print("Naw mate, try again")
        elif ("1" in choice or "sword" in choice) and have_sword != True:
            dead("What sword? The dragon eats your face.")
        elif "2" in choice and have_sword == True:
            dead("Use the damn sword next time...")
        elif "2" in choice:
            dead("Mate, you think you can take a dragon unarmed and alone?")
        elif "3" in choice:
            dead("Shoulda invested in some lessons in dragon language;")
        elif "4" in choice:
            oldShack()
        else:
            print("naw mate, try again")

def dead(why):
    print(why, "you died. well done...")
    print(open("DEAD.txt").read()); time.sleep(2) #prints the text of DEAD.txt as an outro to the game
    exit(0)

def win(how):
    print(how, "You return triumphant to Kind Arthur. \nThe Kingdom shall live in peace another day.")
    print(open("WIN.txt").read()); time.sleep(2) #prints the text of WIN.txt as an outro to the game
    exit(0)

#intro story, do you accept quest? yes -> sphynx room, no-> are u sure?
def start():
    print(open("README.txt").read()); time.sleep(2)  #prints the text of README.txt as an into to the game
    character = buildCharacter() #goes to the buildCharacter funtion, and assigns the results the name character
    print(f"You are {character.name}, a night of King Arther's round table. \nYou have been tasked with finding the Dream Stone \nThe search has clamined many lives. \nYou have 10 health points.")
    time.sleep(1/2)
    choice = input("\nDo you accept?\n> ")

    if "y" in choice:
        sphynx()
    elif "n" in choice:
        print("are you sure?")
        sure = input("> ")

        if "y" in sure:
            print("well that was boring.")
            print(open("DEAD.txt").read()); time.sleep(2)
        elif "n" in sure:
            print("good")
            sphynx()
        else:
            print("Mate, its a yes or no question; are you sure")
    elif "Cheet code" in choice:
        win("You don't deserve this, but fair is fair. \n")

    else:
        start("Only you can decide. Now decide.")

def buildCharacter(): #goes to the class Hero (line 8), and creates the hero.name given by the user
    MyName = input("What is your name, traveler? \n> ")
    return(Hero(MyName, 10)) #takes input and uses that as the object for class Hero
    print(Hero())

start()

Define a method in your class named hurt and a getter for health , like this:在您的 class 中定义一个名为hurt的方法和一个 getter for health ,如下所示:

class Hero(object): #creates class Hero, Hero has-a name and has-a health
    def __init__(self, name, health=10):
        self.name = name
        self.health = health

    def hurt(self,damage):
        self.health-= damage

    def get_health(self):
        return self.health

Then later in the code you can call these methods like this:然后稍后在代码中,您可以像这样调用这些方法:

hero = Hero("mohsen")
hero.hurt(5)
if hero.get_health()<=0:
    exit(0)

I believe this example gets at the question you asked.我相信这个例子得到了你问的问题。

class Hero:
    def __init__(self):
        self.health = 100

Jon = Hero()
Jon.health -= 20
print(Jon.health)

The print statement outputs: 80打印语句输出:80

What you tried would work in another method within your class Hero :您尝试的方法将在您的 class Hero中以另一种方法起作用:

class Hero(object): 
    def __init__(self, name, health=10):
        self.name = name
        self.health = health
        self.alive = True

    def take_damage(self):
        self.health -= 5
        if self.health <= 0:
            self.alive = False

    def is_alive(self):
        return self.alive == True

If you are trying to reduce the health of an object of type Hero , you need to do it via the object reference like this:如果您试图降低Hero类型的 object 的运行状况,您需要通过 object 参考来执行此操作,如下所示:

my_hero = Hero()
my_hero.take_damage()
print(my_hero.is_alive())

Or you can access self.health directly (but better to do it via a method like I showed above):或者您可以直接访问self.health (但最好通过我上面展示的方法来完成):

my_hero = Hero()
my_hero.health -= 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM