8

可能重复:
Python 'self' 关键字

如果这是一个非常愚蠢的问题,请原谅我,但我从来没有理解 Python 中的 self 。它有什么作用?当我看到类似

def example(self, args):
    return self.something

他们在做什么?我想我也在函数的某个地方看到了 args 。请用简单的方式解释:P

4

3 回答 3

14

听起来您偶然发现了 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()
于 2011-07-14T18:26:34.693 回答
6

self是对方法(example在本例中为函数)所属的类的实例的引用。

您需要查看类系统上的 Python 文档,以全面了解 Python 的类系统。您还需要Stackoverflow上查看有关该主题的其他问题的这些答案

于 2011-07-14T18:19:21.670 回答
3

将它作为对当前类实例的引用。在您的示例中,self.something引用了类对象的something属性。example

于 2011-07-14T18:20:58.603 回答