Why should self Python

Before self usage on Python, the first to introduce the lower classes and instances in Python ......
we know that the most important object-oriented concepts is the class (class) and the instances (instance), abstract class is a template, such as students in this abstract things, you can use a Student class to represent. The class and instance are created out of one specific "objects", each object inherits methods from the same class, but each data may be different.
1 to Case of Student, in Python, the class is defined as follows:

class Student(object):
    pass
  
  
  • 1
  • 2

(Object) represents a class inherits from which class down, Object class is the class of all classes will inherit.

2. Example: a good definition of the class, you can create an instance of Student by Student class, create an instance of a name + () implemented by class:

student = Student()
  
  
  • 1

3, due to the class acts as a template, so you can create an instance of the time, we believe the property must be bound mandatory to fill in. The method used here a built-in Python of __init__methods, for example, when the Student class, the name, score tied to other attributes:

class Student(object):
    def __init__(self, name, score):
        self.name = name
        self.score = score
  
  
  • 1
  • 2
  • 3
  • 4

Note here: (1), __init__the first parameter is always method self, creating class represents the instance itself , thus, in the __init__interior of the method, various properties can be bound to the self, because the self points to create an instance of itself. (2), with the __init__method, create an instance in time, you can not pass a null parameter, you must pass the __init__parameter matching method, but do not need to pass self, Python interpreter will own the instance variables pass in:

>>>student = Student("Hugh", 99)
>>>student.name
"Hugh"
>>>student.score
99
  
  
  • 1
  • 2
  • 3
  • 4
  • 5

In addition, this selfrefers to the class itself, self.nameis the Studentproperty of the Variable class is Studentthe class of all. And nameit is coming from outside the parameters, not the Studentkind that comes. Therefore, self.name = nameit means that the external parameters coming from namethe value assigned to their property Student class variables self.name.

4, and as compared to an average number, only one difference in functions defined in the class, is the first parameter is always a class instance variable itselfself , and the call, do not pass this parameter. In addition, methods (functions) like an ordinary function lacks distinction, you can either use the default parameters, variable parameters or keyword parameters ( * args is a variable parameter, args received is a tuple , ** kw keyword parameters, kw received a dict ).

5, since the Student instance of the class itself has data, then to access these data, there is no need to access the function from the outside, and direct access to data within the defined class Student function (method), so that it can "data" encapsulated. These functions are encapsulated data and Student class itself is associated, the method is called class:

class Student(obiect):
    def __init__(self, name, score):
        self.name = name
        self.score = score
    def print_score(self):
        print "%s: %s" % (self.name, self.score)
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
>>>student = Student("Hugh", 99)
>>>student.print_score
Hugh: 99
  
  
  • 1
  • 2
  • 3

As a result, we see from the outside of the Student class, you just need to know, need to create an instance of given name and score. And how to print, it is defined inside the Student class, the data is encapsulated, and the logic, it is easy to call, but do not know the internal details of implementation.

If you want the internal attributes are not externally accessible, you can put before the name of the property plus two underscores , in Python, the instance variable names if the beginning, it becomes a private variable (private), only internal access to, outside can not access, so we altered the Student category:

class Student(object):

    def __init__(self, name, score):
        self.__name = name
        self.__score = score
    def print_score(self):
        print "%s: %s" %(self.__name,self.__score)
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

After the change, for the external code, it changes nothing, but has been unable to access the instance variables from the outside .__nameand instance variables .__scoreof:

>>> student = Student('Hugh', 99)
>>> student.__name
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute '__name'
  
  
  • 1
  • 2
  • 3
  • 4
  • 5

This ensures that external code can not be free to modify the internal state of an object, such protection through access restrictions, code more robust.

But if the external code to get the name and score how to do? Such methods may be increased to get_score get_name and Student class:

class Student(object):
    ...

    def get_name(self):
        return self.__name

    def get_score(self):
        return self.__score
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

If you have to allow external code modifications score how to do? Student can increase set_score method to the class:

class Student(object):
    ...

    def set_score(self, score):
        self.__score = score
  
  
  • 1
  • 2
  • 3
  • 4
  • 5

Note that, in Python, similar to the variable name __xxx__, and it begins with a double underline, double underline and to the end, it is a special variable, special variable that can be accessed directly, not private variables, therefore, can not be used __name__, __score__so variable name.

Sometimes, you'll see an instance variable names beginning with an underscore, such as _name, such as instance variables outside is accessible, however, in accordance with the provisions of the convention, when you see this variable, meaning " Although I can be accessed, but please treat me as a private variable, not free to access. "

Another advantage is that the package at any time to add new methods Student class , such as: get_grade:

class Student(object):
    ...
    def get_grade(self):
        if self.score >= 90:
            return 'A'
        elif self.score >= 60:
            return 'B'
        else:
            return 'C'
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

Similarly, the get_grademethod can be called directly on the instance variables do not need to know the internal implementation details:

>>> student.get_grade()
'A'
  
  
  • 1
  • 2

6, selfcareful usage
(1), examples of self on behalf of the class, not class.

class Test:
    def ppr(self):
        print(self)
        print(self.__class__)

t = Test()
t.ppr()
执行结果:
<__main__.Test object at 0x000000000284E080>
<class '__main__.Test'>
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

Can clearly be seen from the above example, self represent instances of classes. And self.__class__points to the class.
Note: the self into this, the result is the same, but the best use Python convention of self.
(2), Self can not write it?
Within the Python interpreter, when we call t.ppr (), in fact, Python interpreted as Test.ppr (t), which is replaced with examples of the self class.

class Test:
    def ppr():
        print(self)

t = Test()
t.ppr()
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

Results are as follows:

Traceback (most recent call last):
  File "cl.py", line 6, in <module>
    t.ppr()
TypeError: ppr() takes 0 positional arguments but 1 was given
  
  
  • 1
  • 2
  • 3
  • 4

Remind runtime error as follows: ppr no parameters when defining, but we are forced to pass a run-time parameter.

Due to the above explained over t.ppr () is equivalent to Test.ppr (t), so the program reminds us more than pass a parameter t.

Section herein described actually selfcan not be omitted in the definition.

Of course, if we pass the time and not the definition of class instance is invoked, this is a class method.

class Test:
    def ppr():
        print(__class__)

Test.ppr()

运行结果:
<class '__main__.Test'>
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

(3), at the time of succession, which passed instance, it is that the incoming instance, rather than to define an instance of the class of self.

class Parent:
    def pprt(self):
        print(self)

class Child(Parent):
    def cprt(self):
        print(self)
c = Child()
c.cprt()
c.pprt()
p = Parent()
p.pprt()
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

operation result:

<__main__.Child object at 0x0000000002A47080>
<__main__.Child object at 0x0000000002A47080>
<__main__.Parent object at 0x0000000002A47240>
  
  
  • 1
  • 2
  • 3

: Interpretation
should have no problem understanding run c.cprt (), the Child refers to an instance of the class.
However, in operation c.pprt (time) equivalent to Child.pprt (c), it is still self refers to the class of the Child instance, is not defined since self PORT () method, so that looking up along the inheritance tree, found We define pprt () method in the parent class parent in, so there will be a successful call.

(4), the class descriptor, Self descriptor refers to an instance of the class

class Desc:
    def __get__(self, ins, cls):
        print('self in Desc: %s ' % self )
        print(self, ins, cls)
class Test:
    x = Desc()
    def prt(self):
        print('self in Test: %s' % self)
t = Test()
t.prt()
t.x
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

Results are as follows:

self in Test: <__main__.Test object at 0x0000000002A570B8>
self in Desc: <__main__.Desc object at 0x000000000283E208>
<__main__.Desc object at 0x000000000283E208> <__main__.Test object at 0x0000000002A570B8> <class '__main__.Test'>
  
  
  • 1
  • 2
  • 3

The main question here should be: self Desc defined in the class should not be calling it an instance t it? How to become an instance of the class Desc it?
Because this call is tx, that is to say the Test class instance attributes t x, t and since the examples do not define x, so finding the class attributes x, which is an attribute descriptor attribute for instance Desc class only, here and so there is no way Test of the purpose.

So if we call the property directly through the class x you can also get the same results.

The following are the results of the tx changed Test.x run.

self in Test: <__main__.Test object at 0x00000000022570B8>
self in Desc: <__main__.Desc object at 0x000000000223E208>
<__main__.Desc object at 0x000000000223E208> None <class '__main__.Test'>
  
  
  • 1
  • 2
  • 3

Summary: The above is a summary of prior learning when Python, is now presented blog, calling at the same time laying the groundwork for pyspark problem self encountered, the back will contrast java, to be continued .......

Before self usage on Python, the first to introduce the lower classes and instances in Python ......
we know that the most important object-oriented concepts is the class (class) and the instances (instance), abstract class is a template, such as students in this abstract things, you can use a Student class to represent. The class and instance are created out of one specific "objects", each object inherits methods from the same class, but each data may be different.
1 to Case of Student, in Python, the class is defined as follows:

Guess you like

Origin blog.csdn.net/qq_33487726/article/details/91867856
Recommended