可能重复:
Python 'self' 关键字
如果这是一个非常愚蠢的问题,请原谅我,但我从来没有理解 Python 中的 self 。它有什么作用?当我看到类似
def example(self, args):
return self.something
他们在做什么?我想我也在函数的某个地方看到了 args 。请用简单的方式解释:P
可能重复:
Python 'self' 关键字
如果这是一个非常愚蠢的问题,请原谅我,但我从来没有理解 Python 中的 self 。它有什么作用?当我看到类似
def example(self, args):
return self.something
他们在做什么?我想我也在函数的某个地方看到了 args 。请用简单的方式解释:P
听起来您偶然发现了 Python 的面向对象特性。
self
是对对象的引用。它非常接近this
许多 C 风格语言中的概念。看看这段代码:
class Car(object):
def __init__(self, make):
# Set the user-defined 'make' property on the self object
self.make = make
# Set the 'horn' property on the 'self' object to 'BEEEEEP'
self.horn = 'BEEEEEP'
def honk(self):
# Now we can make some noise!
print self.horn
# Create a new object of type Car, and attach it to the name `lambo`.
# `lambo` in the code below refers to the exact same object as 'self' in the code above.
lambo = Car('Lamborghini')
print lambo.make
lambo.honk()
self
是对方法(example
在本例中为函数)所属的类的实例的引用。
您需要查看类系统上的 Python 文档,以全面了解 Python 的类系统。您还需要在Stackoverflow上查看有关该主题的其他问题的这些答案 。
将它作为对当前类实例的引用。在您的示例中,self.something
引用了类对象的something
属性。example