2017-01-26 8 views
-4

私は、Pythonの比較的新しいだと私は、この例でpythonでOOPを実践しようとしてきた:タイプエラー:「strの」オブジェクトが呼び出すことはできません(パイソン)

def get_input(): 
command = input(':').split() 
verb_word = command[0] 
if verb_word in verb_dict: 
verb = verb_dict[verb_word] 
else: 
print('Unkown verb "{}"'.format(verb_word)) 
return 

if len(command) >= 2: 
noun_word = command[1] 
print(verb(noun_word)) 
else : 
print(verb('nothing')) 

def say(noun): 
return "You said '{}'".format(noun) 

class GameObject: 
class_name = "" 
_desc = "" 
health_line = "" 
objects = {} 

def __init__(self,name): 
    self.name = name 
    GameObject.objects[self.class_name] = self 

    def desc(self): 
    return self.class_name + "\n" + self._desc +  "\n" + self.health_line 

class Goblin(GameObject): 
    def __init__(self,name): 
    self.class_name = "goblin" 
    self.health = 3 
    self._desc = 'A foul creature' 
    super().__init__(name) 

@property 
def desc(self): 
    if self.health >= 3: 
    return self._desc 
    elif self.health == 2: 
    health_line = 'It is badly bruised' 
    elif self.health == 1: 
    health_line = 'It is barely standing' 
    elif self.health <= 0: 
    health_line = 'It is dead' 
    return self._desc +'\n'+ self.health_line 

@desc.setter 
def desce(self,value): 
    self.__desc = value 

goblin = Goblin("Gobbly") 

def hit(noun): 
if noun in GameObject.objects: 
    thing = GameObject.objects[noun] 
    if type(thing) == Goblin: 
    thing.health = thing.health - 1 
    if thing.health <= 0: 
    msg = "You killed it" 
    else: 
    msg = "You hit the {}".format(thing.class_name) 
else: 
    msg = "There is no {} here".format(noun) 
return msg 

def examine(noun): 
if noun in GameObject.objects: 
    return GameObject.objects[noun].desc() 
else: 
    return "There is no '{}' here".format(noun) 

verb_dict ={"say":say,"examine":examine,"hit":hit} 

while True : 
get_input() 

それは、このラインと思われます:

return GameObject.objects[noun].des() 

は、タイプエラーを返します。なぜこのことが分かりませんか、私はしばらくこの状態にいました。どんな助けでも大歓迎です。

+8

Guidoを愛する人は、4つのスペースを使用してください! –

+1

正しいインデントでコードを再フォーマットして、他のユーザーがコードを正しく理解できるようにしてください(私はこれを再タブする方法も知らない) –

+0

@Natecat noun_wordを引数にして関数(動詞) – RenWarRen

答えて

0

あなたはDESCの機能を呼び出したい場合は、あなたがそのように行う必要があります:パラメータは、オブジェクトの[名詞]することができ

GameObject.desc(parameter) 

。これは、descメソッドがGameObjectクラスに属しているためです。

関連する問題