Python Learning: 16.Python Face Object (three, reflection, construction method, static field, static method)

Source: Internet
Author: User
Tags reflection

First, the construction method

The __init__ method is automatically executed when an object is created using the class, which is the parentheses after the class.

classA:def __init__(self):Print('A')classB:def __init__(self):Print('B') obj=A ()#Although only the Obj object was created, the __init__ method was executed, the output of a

Derived classes in Python can inherit the constructor of a parent class

1. Based on super ()

Encountering super () means to execute the parent class's XXX property

classA:def __init__(self):Print('A') SELF.TP='Annimal'classB (A):def __init__(self):Print('B') Super (b,self).__init__()        #executes the __init__ method in the parent class B, where self is the obj
#super里的self不是传入后面的__init__方法里, instead of passing directly to the __init__ in a, here super will help you pass the parametersobj=B () output result: BA

2. The constructor of the parent class is executed by the name of the parent class.

classA:def __init__(self):Print('A') SELF.TP='Annimal'classB (A):def __init__(self):Print('B') A.__init__(self)#the name of the parent class is followed by the __init__ ()obj=B () output result: BA

In both of these ways super, when using the second method, to inherit the method of the parent class, you specify the method of the parent class, it looks messy, but when using super, do not let you specify the name of the parent class, this inheritance time according to the normal inheritance rules (described in the previous section).

Second, reflection

viewing object-oriented members with reflection

To go to an object (a module) and manipulate its members as a string

classFoo:def __init__(self,name): Self.name=namedefShow (self):Print('Fshow') R= Hasattr (Foo,'Show')Print(R)#See if there is a show function in the Foo classobj = Foo ('Alexsel') s= Hasattr (obj,'name')Print(s)#See if name exists in obj objectt = hasattr (obj,'Show')Print(t)#See if there is a show this function through the objectoutput Result: Truetruetrue

When we query through the class, we can only find the properties in the class, but when we query through the object created by the class, we not only find the properties in the object (for example, Self.name, which is not found directly in the Class), you can also find methods in the object (such as the show function) because there is a pointer to the class in the object, and when queried through the object, the properties in the class can be found by pointers.

Use reflection to import modules, find classes, create objects, find fields in objects

1. First Use __import__ to import files

function functions are used for dynamic import modules, mainly for reflection or delay loading modules.

__import__ (module) equivalent to import module

2. Import the class using GetAttr (the imported file name, class name)

GetAttr to search for something in a module based on a string

3. Creating an object from a found class

4. Get Properties in an object

Code in the s2.py file

class Foo:     def __init__ (self,name):         = name    def  Show (self):        print('fshow ')

Code in the s1.py file

 m = __import__  ( " ZP   " ) class_name  = GetAttr (m,< Span style= "color: #800000;" > '    ' val  = getattr (Obj, " name   " )    (val) output: Alexsel  

Third, static fields

Static Fields act as duplicates of objects that exist in each object, using static fields to write only one copy of the class.

classFoo:annimal='Cat'    #This is a static field, which is saved in the class.    def __init__(self,name): Temp='Alexsel'        #normal field, stored in object    #common method, stored in class    defShow (self):Print('SH')Print(foo.annimal) output: Cat

When using a static field, use the class name to access the static field first.

Iv. static methods

A static method is a function in a class that does not require an instance. Static methods are mainly used to store logical code, mainly some logic belongs to the class, but there is no interaction with the class itself, that is, in a static method, the operation of the methods and properties in the class is not involved.

classFoo:annimal='Cat'    def __init__(self):Pass    defShow (self):Print('SH')    #Decorator , using this adorner to decorate a method in a class, this method becomes a static method@staticmethoddefout ():Print(' out') foo.out ()#There is no need to pass self in a static method, so accessing a static method takes precedence over the use of classes to accessobj =Foo () obj.out () output result: Outout

Static methods allow us to execute methods in a class without having to create an object.

V. Types of methods

A class method is a way to manipulate the class itself as an object. The difference between him and the static method is that whether this is called from an instance or from a class, it uses the first parameter to pass the class over .

classFoo:annimal='Cat'    def __init__(self):Pass    defShow (self):Print('SH')    #Decorator , using this adorner to decorate a method in a class, this method becomes a class method@classmethoddefout (CLS):Print(' out', CLS) Foo.out ()#Class method, the class is automatically passed to the CLS of the class methodoutput Result: Out<class '__main__. Foo'>

Python Learning: 16.Python Face Object (three, reflection, construction method, static field, static method)

Related Article

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.