-->

What does self do? [duplicate]

2019-04-07 06:54发布

问题:

Possible Duplicate:
Python 'self' keyword

Forgive me if this is an incredibly noobish question, but I never did understand self in Python. What does it do? And when I see things like

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

what do they do? I think I've seen args somewhere in a function too. Please explain in a simple way :P

回答1:

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


回答2:

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.



回答3:

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.



标签: python self args