自我做什么?

7 python self args

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

请原谅我,如果这是一个令人难以置信的noobish问题,但我从来没有在Python中理解自我.它有什么作用?当我看到类似的东西时

def example(self, args):
    return self.something
Run Code Online (Sandbox Code Playgroud)

他们在做什么?我想我也在某个功能中看到了args.请以简单的方式解释:P

Tri*_*ych 12

听起来你偶然发现了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()
Run Code Online (Sandbox Code Playgroud)


Sea*_*ira 5

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

您将需要查看类系统上Python文档,以全面介绍Python的类系统.您还希望Stackoverflow 查看有关该主题的其他问题的这些答案 .