从 Python 中的类中的函数获取返回值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14768162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the return value from a function in a class in Python
提问by user1875195
I am trying to simply get the value out of my class using a simple function with a return value, I'm sure its a trivial error, but im pretty new to python
我试图使用带有返回值的简单函数简单地从我的类中获取值,我确定这是一个微不足道的错误,但我对 python 很陌生
I have a simply class set up like this:
我有一个简单的类设置如下:
class score():
#initialize the score info
def __init__(self):
self.score = 0
self.num_enemies = 5
self.num_lives = 3
# Score Info
def setScore(num):
self.score = num
# Enemy Info
def getEnemies():
return self.num_enemies
# Lives Info
def getLives():
return self.getLives
etc.....
Than I create an instance of the class as such:
比我这样创建类的实例:
scoreObj = score()
for enemies in range(0, scoreObj.getEnemies):
enemy_sprite.add(enemy())
I get the error saying that an integer is expected, but it got an instancemethod
我收到错误消息,指出需要一个整数,但它有一个实例方法
What is the correct way to get this information?
获取此信息的正确方法是什么?
Thanks!
谢谢!
采纳答案by Joshua Clayton
The first parameter for a member function in python is a reference back to the Object.
python中成员函数的第一个参数是对对象的引用。
Traditionally you call it "self", but no matter what you call the first parameter, it refers back to the "self" object:
传统上你称它为“self”,但无论你如何称呼第一个参数,它都指向“self”对象:
Anytime I get weird errors about the type of a parameter in python, I check to see if I forgot the self param. Been bit by this bug a few times.
每当我在 python 中遇到关于参数类型的奇怪错误时,我都会检查是否忘记了 self 参数。被这个错误咬了几次。
class score():
#initialize the score info
def __init__(self):
self.score = 0
self.num_enemies = 5
self.num_lives = 3
# Score Info
def setScore(self, num):
self.score = num
# Enemy Info
def getEnemies(self):
return self.num_enemies
# Lives Info
def getLives(foo): #foo is still the same object as self!!
return foo.num_lives
#Works but don't do this because it is confusing
回答by Gareth Webber
getEnemiesis a function, so call it like any other function scoreObj.getEnemies()
getEnemies是一个函数,所以像任何其他函数一样调用它 scoreObj.getEnemies()
回答by Ketouem
You made a simple mistake:
你犯了一个简单的错误:
scoreObj.getEnemies()
回答by BrenBarn
scoreObj.getEnemiesis a reference to the method. If you want to call it you need parentheses: scoreObj.getEnemies().
scoreObj.getEnemies是对方法的引用。如果要调用它,则需要括号:scoreObj.getEnemies().
You should think about why you are using a method for this instead of just reading self.num_enemiesdirectly. There is no need for trivial getter/setter methods like this in Python.
您应该考虑为什么要为此使用一种方法,而不仅仅是self.num_enemies直接阅读。在 Python 中不需要像这样的简单的 getter/setter 方法。
回答by Torxed
This code works:
此代码有效:
class score():
def __init__(self):
self.score = 0
self.num_enemies = 5
self.num_lives = 3
def setScore(self, num):
self.score = num
def getEnemies(self):
return self.num_enemies
def getLives(self):
return self.getLives
scoreObj = score()
for enemy_num in range(0, scoreObj.getEnemies()):
print enemy_num
# I don't know what enemy_sprite is, but
# I commented it out and just print the enemy_num result.
# enemy_sprite.add(enemy())
Lesson Learned:
学过的知识:
Class functions must alwaystake one parameter, self.
That's because when you call a function within the class, you always call it with the class nameas the calling object, such as:
类函数必须始终采用一个参数self. 那是因为当你在类中调用一个函数时,你总是以类名作为调用对象来调用它,比如:
scoreObj = score()
scoreObj.getEnemies()
Where xis the class object, which will be passed to getEnemies()as the root object, meaning the first parameter sent to the class.
在哪里x是类对象,它将getEnemies()作为根对象传递给,意思是发送给类的第一个参数。
Secondly, when calling functions within a class (or at all), always end with ()since that's the definition of calling something in Python.
其次,在类中调用函数(或根本不调用)时,总是以 结尾,()因为这是在 Python 中调用某些东西的定义。
Then, ask yourself, "Why am I not fetching 'scoreObj.num_lives' just like so instead? Am I saving processing power?"Do as you choose, but it would go faster if you get the values directly from the class object, unless you want to calculate stuff at the same time. Then your logic makes perfect sense!
然后,问问自己,“为什么我不像这样获取 'scoreObj.num_lives'?我是在节省处理能力吗?” 按照你的选择去做,但如果你直接从类对象中获取值会更快,除非你想同时计算东西。那么你的逻辑是完全有道理的!

