如何在课程中打印变量'如果声明?

时间:2016-10-17 03:47:36

标签: python-3.x

我尝试使用以下代码在Python中打印变量:

from time import sleep
import random

class Hero:
    def __init__(self,name):
        self.name = name

        if name == "rock":
            self.health = 50
            self.attack = 10

        elif name == "paper":
            self.health = 70
            self.attack = 7

        elif name == "scissors":
            self.health = 100
            self.attack = 5

    def dmg(self, other):
        other.ehealth -= self.attack

start = 1

while start == 1:
    name = input("Pick a class [rock/paper/scissors]")

    if name != "rock" or "paper" or "scissors":
        print ("That player does not exist. Try again.")
        start = 1

    else:
        start = 1

    player = Hero(name)
    enemyName = ["erock", "epaper", "escissors"]
    ename = random.choice(enemyName)

    print ("Your character is", name, "which comes with", self.health, "health, and", self.attack, "attack.")
    print("")

    sleep(1)

    print ("Your enemy is", ename, "which comes with", ehealth, "health, and", eattack, "attack.")

我无法找到一种方法来访问和打印变量" self.health"在" Hero"类。我可以访问" name"正好。也许它是在if声明下的事实?有人可以帮助我吗?

1 个答案:

答案 0 :(得分:2)

self只是方法中使用的参数名称。不要在方法之外使用它。

要访问变量,请使用对象名称(player)来引用它们,如下所示

player.health

您正在打印的name变量“有效”,因为它不是来自对象。您也应该使用相同的表示法来访问它:

player.name