2017-03-25 4 views
-1

문자 클래스를 작성하는 함수와 주 코드가있는 모듈이있는 프로그램과 같은 전투를하고 있습니다. 여기 다른 모듈에서 함수 가져 오기 : AttributeError : 'module'객체에 속성이 없습니다.

AttributeError: 'module' object has no attribute 

함수이다 : 나는 문자 중 하나의 상태를 변경하는 함수를 가져 오면 내가 말하는 오류가

def changeHealth(self,health,defense,Oattack): 
    self.health = health - (Oattack - defense) - 15 
    return self.health 

나는 주 코드 모듈의 함수를 호출 할 때 나는이 작업을 수행 :

import CharacterClass 
CharacterClass.changeHealth(self,health,defense,Oattack) 
+1

'self = Character()'이것은 제거되어야합니다. 파이썬에서는 이것을하지 마십시오. – Julien

+1

접근 방식에는 많은 문제점이 있습니다. 하나의 클래스 정의 내에서 함수를 재정의하고 사용하지 않는 변수를 생성합니다 ('self = Character()'는 결코 액세스하지 않는 클래스 변수를 만듭니다). 데이터 모델을 변경하십시오. 프로그램에서 주인공과 상대방을 '캐릭터'로 만들 수 있습니다 (클래스 내부가 아님). 그런 다음 주인공과 상대방의 속성에 액세스하고 각자의 건강을 적절하게 변경하는 '전투'기능을 사용하십시오. – Craig

+0

@Craig, 어떻게 상대를 만들 수 있습니까? self = Character() –

답변

0

이 다음은 프로그램의 모든 문자에 사용될 수 Character에 대한 클래스를 만들 수있는 방법의 예입니다. 각 클래스는 고유 한 유형의 객체 (이 경우 "문자")를 나타내야합니다. 각 문자는 해당 클래스의 인스턴스 여야합니다. 그런 다음 함수 또는 클래스 메서드를 사용하여 문자 인스턴스 간의 상호 작용을 처리합니다.

class Character(object): 
    def __init__(self, name, attack, defense, health): 
     self.name = name 
     self.attack = attack 
     self.defense = defense 
     self.health = health 

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

    def __str__(self): 
     return "Character: {}, A:{}, D:{}, H:{}".format(self.name, self.attack, self.defense, self.health) 

    def check(self): 
     print("this works") 

    def doAttack(self, other=None): 
     dmg = self.attack - other.defense 
     if dmg > 0: 
      other.injure(dmg) 
      print("{} caused {} damage to {}".format(self.name, dmg, other.name)) 
     else: 
      print("{} did not injure {}".format(self.name, other.name)) 


hero = Character('Hero', 8, 10, 20) 
opponent = Character('Monster', 4, 5, 10) 


opponent.doAttack(hero) 
print(hero) 
print(opponent) 
print() 

hero.doAttack(opponent) 
print(hero) 
print(opponent) 
print() 

이 코드를 실행하면 생성합니다

Monster did not injure Hero 
Character: Hero, A:8, D:10, H:20 
Character: Monster, A:4, D:5, H:10 

Hero caused 3 damage to Monster 
Character: Hero, A:8, D:10, H:20 
Character: Monster, A:4, D:5, H:7 

이것은 아주 기본적인 예이다. Object Oriented Programming in Python (또는 이와 유사한 텍스트)을 읽으면 객체 지향 코드를 구조화하는 개념을 배울 수 있습니다.

+0

죄송합니다. @Craig Stack Overflow를 사용하면 다른 질문을 추가 할 수 없습니다. 지난 2 일 동안 너무 많은 질문을 던졌기 때문에 1 번만 요청했습니다. 새 질문에 대한 질문을 편집해야했습니다. 당신의 대답은 말이되지 않을 수도 있습니다. 원하는 경우 삭제하십시오. –

관련 문제