<分区>
Possible Duplicate:
Python 'self' keyword
如果这是一个非常菜鸟的问题,请原谅我,但我从来没有在 Python 中理解 self。它有什么作用?当我看到类似的东西时
def example(self, args):
return self.something
他们是做什么的?我想我也曾在某个函数的某处看到过 args。请用简单的方式解释:P
<分区>
Possible Duplicate:
Python 'self' keyword
如果这是一个非常菜鸟的问题,请原谅我,但我从来没有在 Python 中理解 self。它有什么作用?当我看到类似的东西时
def example(self, args):
return self.something
他们是做什么的?我想我也曾在某个函数的某处看到过 args。请用简单的方式解释:P
最佳答案
听起来您已经无意中发现了 Python 的面向对象特性。
self
是对对象的引用。它与许多 C 风格语言中的 this
概念非常接近。查看这段代码:
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()
关于python - self 做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6698030/