Explaining the python 'self' variable to a

2019-01-03 05:12发布

This question already has an answer here:

I'm pretty much ignorant of OOP jargon and concepts. I know conceptually what an object is, and that objects have methods. I even understand that in python, classes are objects! That's cool, I just don't know what it means. It isn't clicking with me.

I'm currently trying to understand a few detailed answers that I think will illuminate my understanding of python:

  1. What does the "yield" keyword do in Python?
  2. What is a metaclass in Python?

In the first answer, the author uses the following code as an example:

>>> class Bank(): # let's create a bank, building ATMs
...    crisis = False
...    def create_atm(self) :
...        while not self.crisis :
...            yield "$100"

I don't immediately grok what self is pointing to. This is definitely a symptom of not understanding classes, which I will work on at some point. To clarify, in

>>> def func():
...   for i in range(3):
...     print i

I understand that i points to an item in the list range(3) which, since it is in a function, isn't global. But what does self "point to"?

8条回答
老娘就宠你
2楼-- · 2019-01-03 05:49

The reason "self" is there (by convention) is that when the Python runtime sees a call of the form Object.Method(Param1,Param2), it calls Method with parameters (Object,Param1,Param2). So if you call that first parameter "self", everyone will know what you are talking about.

The reason you have to do this is the subject of another question.

As far as a metaclass, it's something rarely used. You might want to look at: http://python-history.blogspot.com/2009/04/metaclasses-and-extension-classes-aka.html, the original author and current Benevolent Dictator For Life of Python explains what this is, and how it came to be. He also has a nice article on some possible uses, but most people never directly use it at all.

查看更多
ら.Afraid
3楼-- · 2019-01-03 05:55

self refers to an instance of the class.

查看更多
登录 后发表回答