The method of the Python class self as the first parameter action is what

Source: Internet
Author: User
Tags class definition in python

Why does the Python class method need to add self as the first argument? For example, the Python class method is defined in this way:

Class Charfield (Field):
Description = _ ("String (up to% (max_length) s)")

def __init__ (self, *args, **kwargs):
Super (Charfield, self). __init__ (*args, **kwargs)
Self.validators.append (validators. Maxlengthvalidator (Self.max_length))

def check (self, **kwargs):
Errors = Super (Charfield, self). Check (**kwargs)
Errors.extend (Self._check_max_length_attribute (**kwargs))
return errors

See an article about this problem, reprinted over.


The Concise Python tutorial describes the use of self as follows:

The methods of a class have only one particular difference from a normal function-they must have an extra first parameter name, but you don't assign a value to this parameter when you call the method, and Python provides that value. This particular variable refers to the object itself, and by convention its name is self.

Although you can give this parameter any name, it is strongly recommended that you use the name self-other names are not in favor of your use. There are many advantages to using a standard name--your program readers can quickly identify it, and if you use self, there are also IDES (integrated development environments) that can help you.

Self in Python is equivalent to the self pointer in C + + and the This reference in Java, C #.

You must be wondering how Python assigns a value to self and why you don't need to assign it a value. An example would make this clear. Suppose you have a class called MyClass and an instance of this class MyObject. When you call the object's method Myobject.method (Arg1, arg2), it automatically transitions from Python to Myclass.method (MyObject, Arg1, arg2)-that's the principle of self.

This also means that if you have a method that does not require a parameter, you still have to define a self parameter for the method.

I'm here to add a few example programs to deepen my understanding:

Class Person:
def sayhi (self):
print ' Hello,how are you? '
P=person ()
P.sayhi ()
The results appear as follows:

Hello,how Are you?

Change it.


Class Person:
def sayhi (self):
print ' Hello,how are you? '
P=person ()
Person.sayhi (P)
Knot is ditto!

Change it again: what happens when you remove self? )


Class Person:
Def sayhi ():
print ' Hello,how are you? '
P=person ()
Person.sayhi (P)
P.sayhi ()
The following error message appears:

Traceback (most recent call last):
File "C:\pro\Person2.py", line 5, in?
Person.sayhi (P)
Typeerror:sayhi () takes no arguments (1 given)

__NAME__ is used to identify a state in which a module is directly running or as a generic module being imported. When a module is run directly, __name__ equals __main__, and if it is imported as a generic module, __name__ is the name of the module itself.

Example:


if __name__ = = "__main__":
Run ()
Self is a convention. In Python, the first parameter of a class method represents the object itself, and self is generally used in Python. You can also use this.

Example:

A is the way you want to use it. But self is a promise. When you call a method of an object, the object itself is passed in as the self parameter. Such as:

Class A:
Def p (self, name):
Print Name
A=a ()
A.P (' AA ')
At this time, the equivalent of A.P (A, ' AA ')

Python objects do not necessarily have __init__ methods, whether they are base classes or subclasses. Because __init__ is not a constructor, the Python object is constructed when it calls __init__, which is called "initialization" more appropriate.

If an object is a subclass and needs to have __init__, the first statement in __init__ is the __init__ of the parent class (unless the parent class is a built-in data type like dict and does not need __init__). After the call is done, the associated initialization of the subclass is overridden as a method.

Typically, a subclass overrides the "proprietary class method" and triggers the associated action, which allows for more advanced initialization without using __INIT__.

If the subclass's method overrides the parent class, what about the method of calling the parent class? Python is not super. Very simple, direct "parent class name. Method".

What is the difference between a property that is generally defined in the class definition and the attribute in the method, called a class attribute? Class properties can be invoked without having to generate an instance, and the properties embedded within the method (especially those generated by the __INIT__ initialization) must have an instance before it can be invoked.

All instances of a class have a uniform "class attribute", so is the "class attribute" The constant of the class? No! By invoking self.__class__ in any instance. Name can modify the class properties, and all instances will apply this new class attribute. SELF.__CLASS__ represents a reference to a class, does not represent any instance, and the instance is self.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.