2016-10-17 2 views
0

나는 다음과 같은 코드를 사용하여 파이썬에서 변수를 인쇄하려고 해요 : 나는 "영웅"클래스에서 변수 "self.health"에 접근하고 인쇄 할 수있는 방법을 알아낼 수 없습니다클래스 'if 문 내에서 변수를 인쇄하는 방법은 무엇입니까?

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.") 

. "이름"에 액세스 할 수 있습니다. if 문 아래에 있다는 사실인가? 누군가 나를 도울 수 있습니까?

+0

코드의 들여 쓰기를 해결할 수 있습니까? 코드가 현재 형식으로 어떻게 보이는지 알려주지 않습니다. –

답변

2

self은 메서드 내에서 사용되는 매개 변수 이름입니다. 메서드 외부에서 사용하지 마십시오.

는 변수가 객체로부터 아니기 때문에 당신이 "작품"을 인쇄하는이

player.health 

name 변수와 같은 개체 이름 (player) 사용을 참조에 액세스하려면. 동일한 표기법을 사용하여 액세스해야합니다.

player.name 
관련 문제