What does self do? [duplicate]

梦想的初衷 提交于 2019-12-04 04:35:03

It sounds like you've stumbled onto the object oriented features of Python.

self is a reference to an object. It's very close to the concept of this in many C-style languages. Check out this code:

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()
Sean Vieira

self is the reference to the instance of the class that the method (the example function in this case) is of.

You'll want to take a look at the Python docs on the class system for a full introduction to Python's class system. You'll also want to look at these answers to other questions about the subject on Stackoverflow.

Self it a reference to the instance of the current class. In your example, self.something references the something property of the example class object.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!