问题
class Character:
def __init__(self):
self.name = ""
self.health = 1
self.health_max = 1
class Player(Character):
def __init__(self):
Character.__init__(self)
self.state = 'normal'
self.health = 10
self.health_max = 10
class Monster(Character):
def Dragon(self):
self.name = "Dragon"
self.health = 20
def Goblin(self):
name = "Goblin"
health = 5
p = Player()
p.name = raw_input("Please enter your name: ")
print p.name
print p.state
print p.health
print p.health_max
m = Monster()
enemy = m.Dragon
print enemy.name
print enemy.health
Sorry, I've made this a little simpler to explain what I'm having difficulty with. I'm having a little bit of trouble with the basics of OOP, and I'm running into an issue with this snippet of code. I'm trying to create a "Dragon" here but I'm running into the following error:
Traceback (most recent call last): File "test2.py", line 32, in print enemy.name AttributeError: 'function' object has no attribute 'name'
Can you tell me what I'm doing wrong here? Thanks.
回答1:
You have to create an instance of a class first before you call any functions from it:
myenemy = Enemy()
myenemy.Dragon()
In your code, it looks like you created self.enemy
, but later you call self.enemy = Enemy.Dragon(self)
. Instead of this last line, put self.enemy = self.enemy.Dragon(self)
.
It seems to be a recurring issue in the rest of your code as well. Commands = {'explore': Player.explore}
should probably be Commands = {'explore': p.explore}
(after you have created the instance p
).
Since your updated code, I think you're getting functions and classes mixed up. Dragon
is a function, and when you do enemy = m.Dragon
, you are simply copying the function onto enemy. And thus when you do enemy.name
, thinking it's a class, an error is raised, because enemy
is now a function, not an instance.
You will have to create separate classes for different monsters:
class Dragon:
self.name = "Dragon"
self.health = 20
class Goblin:
name = "Goblin"
health = 5
来源:https://stackoverflow.com/questions/17437837/error-unbound-method-dragon-must-be-called-with-enemy-instance-as-first-argu