开发者

What does self do? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Python 'self' keyword

Forgive me if this is an开发者_Go百科 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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜