python0.16------Constructors/Destructors/self details/overrides/Access Restrictions/object properties and Class Properties/@property/Operator overloading

Source: Internet
Author: User
Tags class definition

constructor: __init__ ()
Intro: Because everyone is born different. Therefore, if there is a problem in assigning a value directly to the class element in the person class, it will cause everyone to have the same initial state, which is incompatible with the logic of nature. Should be based on the characteristics of each person, to each person born different characteristics. This idea can be implemented through constructors. The __init__ () function uses the class to create an automatic call to an object. Note: If you do not explicitly write out the constructor, an empty constructor is added by default.

using constructors:
def __init__ (self,name,age,height,weight): #一般定义属性在构造函数里面定义.
self.name=name #self. Name indicates that a property is created for the current object.
self.age=age #self. Age indicates that a property is created for the current object.
self.height=height #self. Height indicates that a property is created for the current object.
self.weight=weight #self. Weight represents a property created for the current object.
#当在person后面加实参时, the __init__ () function is actually called.

#调用

per1=person (' Qie ', 18,180,60).
per2=person (' Bob ', 22,170,65 )。
so per1 and Per2 are not the same at birth.


destructors: (rarely used when programming)
__del__ () indicates that an object is automatically called when it is disposed.
Principle of Object Release: Reference counter principle. When creating an object, there is an attribute num=1, when there is a place to use it, there is a strong pointer to it, NUM+1, releasing a strong pointer, num-1. When num is 0 o'clock, the system automatically releases this object. The destructor is then called.
When the program finishes, the object is freed and the destructor is called.
If the object is forcibly disposed, use the del instruction. The system then calls the destructor.
The objects defined inside the function are automatically released at the end of the function, which can be used to reduce the waste of memory space. The destructor is then called.

Self Explanation:
Self is not a keyword, and self can be replaced by any identifier, but it is generally used with self.
Self represents an instance of a class, not a class.
which object invokes the method, then self in the method represents which object.
self.__class__ represents the class name and can only be used in the definition of a class.
For example:
def run (self):
per=self.__class__ (' Bob ', 1,1,1)
print (PER)
represents the creation of an object inside the Run method called per.


rewrite : Write the method of the class definition again.

Intro: If an object has 100 properties and wants to print them all, it should generally be written as: print (PER.A,PER.B,PER.C,PER.D,.........., per.n100). But there are too many properties, so it is tiring to write code. It would be nice if you could print all the properties directly with print (per). Therefore, rewriting __str__ () and __repr__ () will satisfy the requirements.

Example: Overriding the __str__ () and __repr__ () methods
The __str__ () method #它是给程序员用的, which is called automatically when you call execute print (object name).
The __repr__ () method #它是给机器用的, which is called after the object name is hit directly in the Python interpreter. For example: In the black screen terminal, directly knocking on the object, it will call __repr__ ().

Note: 1: __str__ (), __repr__ () needs a return value, the return value directly replaces the per!!! inside print At the same time, if the __str__ () method is not defined, only the __repr__ () method is defined, then the __repr__ () method is called when print (per) is called.

Access Restrictions:
If I have a property of 100 dollars, if I can modify it directly outside of the class, someone else can easily tamper with my change amount. This is obviously unreasonable. To make the properties of an object not directly accessible externally. You can precede the property with two underscores . In Python, if you precede a property with two underscores, this property is equivalent to a private property. Private variables cannot be accessed externally, and private variables can be accessed inside the class.
You can change the money in the class by customizing the method to assign and value the private property:
For example, a class has a private variable __money
def Getmoney (self):
return __money
def Setmoney (Self,money):
if money<0:
self.__money=0
Else:
Self.__money=money

The Per.__money is not directly accessible because the Python interpreter interprets __money as __person__money, and if you directly access __person__money, you can succeed. But it is highly recommended not to do so. and different versions of the interpreter may exist to explain the inconsistency of the variable name of the hardship.

In Python, __XXX__ is a special variable, not a private variable, and the value of a special variable can be accessed directly. Indicates that the system has been written and has some special meanings.

In Python _XXX variable, external is also accessible. However, in accordance with the Convention rules, when I see such variables. It means ' although I can be accessed, but please treat me as a private variable, do not visit me directly.

Object properties and Class properties:

Class Properties:
class Person (object):
Name= "Person" #类属性
def __init__ (self,name):
Self.name=name #对象属性

Object properties have precedence over class properties. do not use object properties with the same name as class properties. Because object properties are masked out of class properties. However, when you delete an object property, the class property is called again when you use it. Such properties are not controllable.

can Dynamically adding object properties to an object , which is only valid for the current object, has no effect on other objects created by the class.
For example:
class Person:
pass
Person=person ()
#动态添加属性:
Person.name= ' Bob '

#动态添加方法:
Introduce the Methodtype () method of the types class first
From types Import methodtype () #偏函数, equivalent to passing the object in itself
Def say (self):
Print (' My name is ' +self.name)
Per.speak=methodtype (Say,per) #此时per对象就有了speak方法. In fact, the Methodtype () function is a biased function, let the say function self default assignment to the object name, and then assign the modified function to the speak variable.

Note: If you want to restrict the properties of an instance to only Name,age,weight, other properties cannot be added. Then, when defining a class, you can define a special attribute (__slots__). You can limit the properties that are added dynamically.
For example:
Class Person:
__slots__= (' name ', ' age ') #这样只能动态地增加name, age two attributes, including methods. For example: A person cannot fly, and therefore cannot give a way to fly.

Property :
use object. property to access and change object properties more easily than objects. Method () To change and access the object's properties.
For example:
class Person:
def __init__ (self,age):
Self.__age=age
@property #访问
def Age (self):
return Self.__age
@age. Setter #修改
def Age (self):
if Self.__age<0
self.__age=0
Else:
Self.__name=age

Print (Per.age) #相当于getAge ()
Per.age=1 #相当于SetAge (1)
Note that this does not equal the direct manipulation of private variables, because the assignment of private variables is limited.

operator Overloading (' + ' operator overloading is most commonly used):

Intro: Print (1+2) Output 3
Print (' 1 ' + ' 2 ') outputs ' #说明不同类型用加法会有不同的解释, which means that the ' + ' operator has different functions in different types of objects, that is, the ' + ' operator is overloaded in each class.

#然而, create a custom instance of the class person, but not add it, why? Because operator overloading is not performed!!!
Per1=person (1)
Per2=person (2)
Print (per1+per2) #输出错误 because ' + ' has no explanation for the person type.

#解决方法:

def __add__ (Self,other):
return person (self.num+other.num) #运算符重载, remember to return a value oh, here is an object with an initial value of 3 oh.
def __str__ (self):
The return ' num= ' str (self.num) #重写__str__ () method, which is intended to print some values about an object directly when the print (object) is called.

Call: Print (PER1+PER2) equivalent to print (per1.__add__ (PER2))

python0.16------Constructors/Destructors/self details/overrides/Access Restrictions/object properties and Class Properties/@property/Operator overloading

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.