2017-03-25 74 views
-1

我正在進行一場類似於程序的戰鬥,其中有一個模塊包含創建字符類的函數和一個主代碼。當我輸入一個函數來改變人物之一的健康,我得到一個錯誤說:從另一個模塊導入函數:AttributeError:'模塊'對象沒有屬性

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()'這個應該被移除 - 你不要在Python中這樣做。 – Julien

+1

你的方法有很多問題。您正在重新定義一個類定義中的函數,並創建您未使用的變量('self = Character()'創建一個您從不訪問的類變量)。嘗試更改數據模型。你可以在程序中創建主角和對手作爲「角色」(不在課堂內)。然後有一個「戰鬥」功能,可以訪問主角和對手的屬性,並根據需要改變每個角色的健康狀況。 – Craig

+0

@克雷格,我將如何創建我的對手?是我的代碼在正確的軌道上,除了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個問題......我不得不將問題編輯爲我的新問題你的回答可能沒有意義。隨意刪除它,如果你想 –

相關問題