Python learning diary (xxvii) reflection and a few built-in functions

isinstance()

Analyzing isinstance (obj, cls) whether the object obj in class cls

class Person:
    def __init__(self,name):
        self.name = name
p = Person('Jane')
print(isinstance(p,Person))       #True

issubclass()

Analyzing issubclass (sub, super) sub whether the super class derived from

class Person:
    def __init__(self,name):
        self.name = name
class Father(Person):
    pass
print(issubclass(Father,Person))    #True
print(issubclass(Person,Father))    #False

reflection

Reflex is to use a string to type the name of the operating variables, python in all things are all objects (can use reflection)

Lkhsattr ()

A function for determining whether an object contains attributes corresponding getattr usually used together with, first determines whether the object contains hasattr this property, if it has come and collect by getattr value, if not not suggest this property

class Person:
    age = 20
    def __init__(self,name,height,weight):
        self.name = name
        self.height = height
        self.weight = weight
    def fuc(self):
        print('weight...height...')
#1
if hasattr(Person,'age'):
    print(getattr(Person,'age'))          #20
else:
    print(' Do not have this class attribute! ' ) 
# 2 
P = the Person ( ' Adson ' , 1.6,75 )
 IF the hasattr (P, ' BMI ' ):
     Print (getattr (P, " BMI " ))
 the else :
     Print ( ' no such ! properties ' )                # do not have this property! 
# 3 IF hasattr (the p-, ' Fuc ' ): 
    getattr (the p-, ' Fuc ' ) ()                    # weight ... height ...

the else :
     Print ( ' not this way! ' )

2.getattr()

Function returns the attribute value of an object

Attribute (1) reflecting object

class A:
    def __init__(self,name):
        self.name = name
a = A('Adson')
ret = getattr(a,'name')
print(ret)                      #Adson

(2) reflecting object

class A:
     DEF Fuc (Self):
         Print ( ' ! This IS Fuc ' ) 
A = A () 
RET = getattr (A, ' Fuc ' )
 Print (RET)                   # . <bound Method A.fuc of <__ main __ A Object at 0x00000000024E1C88 >> obtain the address of a binding method of 
ret ()                        # This iS Fuc! parentheses to call the method after ret

(3) the reflective properties of the class

class A:
    age = 18
ret = getattr(A,'age')
print(ret)                 #18

(4) The method of reflection type (classmethod, staticmethod)

The general approach is to call the class name. Method name

class A:
    @classmethod
    def fuc(cls):
        print('This is class fuc!')
ret = getattr(A,'fuc')
print(ret)              #<bound method A.fuc of <class '__main__.A'>>  获得一个绑定方法
ret()                   #This is class fuc!
getattr(A,'fuc')()      #This is class fuc! 简写

Variable (5) of the reflection module

First establish a module, the module name pyfile.py, add a variable

dic = {'apple' : 18,'banana' : 20}

Then through my reflection module module variables

import pyfile
print(pyfile.dic)                        #{'apple': 18, 'banana': 20}
ret = getattr(pyfile,'dic')
print(ret)                               #{'apple': 18, 'banana': 20}

Method (6) of the reflection module

First establish a module, the module name pyfile.py, add a method

def fuc():
    print('abc123aaa!!!')

Then through my module module reflection method

import pyfile
ret = getattr(pyfile,'fuc')
print(ret)                             #<function fuc at 0x0000000002498D08>
ret()                                  #abc123aaa!!!
getattr(pyfile,'fuc')()                #abc123aaa!!!

Class (7) of the reflection module

Import pyfile 
b = getattr (pyfile, ' B ' ) ( ' Josn ' )            # getattr equivalent to get Class B of this module is a b instantiate objects 
Print (b. the __dict__ )                          # { 'name': 'Josn '} 
Print (b.price)                             # 200 is 
b.fuc ()                                    # This classB fuc..Josn

(8) reflecting the self-module variable

By sys.modules [ '__ main__'] to find the current module

import time
import sys
t = time.asctime(time.localtime(time.time()))
print(t)                                        #Mon Sep  9 22:36:40 2019
print(sys.modules['__main__'])                  #<module '__main__' from 'C:/Users/Administrator/PycharmProjects/PYL/temp_file/temp_py.py'>
print(sys.modules['__main__'].t)                #Mon Sep  9 22:38:01 2019
ret = getattr(sys.modules['__main__'],'t')
 Print (right)                                       # Sun Sep 9 22:39:05 2019

(9) The method of the reflection module itself

import sys
def fuc():
    print('abc123...')
ret = getattr(sys.modules['__main__'],'fuc')
print(ret)                                    #<function fuc at 0x0000000002798730>
ret()                                         #abc123...
getattr(sys.modules['__main__'],'fuc')()      #abc123...

3.setattr()

Set the attribute values, the attribute is not necessarily present

class Person:
    age = 20
    def __init__(self,name,height,weight):
        self.name = name
        self.height = height
        self.weight = weight
#对一个对象修改
p = Person('Adson',1.6,75)
setattr(p,'name','Jane')
setattr(p,'height',1.7)
setattr(p,'gender','male')
print(p.__dict__)                   #{'name': 'Jane', 'height': 1.7, 'weight': 75, 'gender': 'male'}
#对一个类修改
print(Person.__dict__)              #{'__module__': '__main__', 'age': 20, '__init__': <function Person.__init__ at 0x0000000002548950>,
                       '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__':
                       <attribute '__weakref__' of 'Person' objects>, '__doc__': None}
setattr(Person,'age',21) setattr(Person,'name','Jane') setattr(Person,'height',1.7) setattr(Person,'gender','male') print(Person.__dict__) #{'__module__': '__main__', 'age': 21, '__init__': <function Person.__init__ at 0x0000000002548950>,
                       '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__':
                       <attribute '__weakref__' of 'Person' objects>, '__doc__': None,
                       'name': 'Jane', 'height': 1.7, 'gender': 'male'}

Here except that they store different values ​​namespace objects and classes

4.delattr()

Properties for deleting

class Person:
    age = 20
    def __init__(self,name,height,weight):
        self.name = name
        self.height = height
        self.weight = weight
p = Person('Adson',1.6,75)
print(p.__dict__)                   #{'name': 'Adson', 'height': 1.6, 'weight': 75}
delattr(p,'height')
print(p.__dict__)                   #{'name': 'Adson', 'weight': 75}
print(Person.__dict__['age']) #20 delattr(Person,'age') print(Person.__dict__['age']) #KeyError: 'age'

 

Built-in class methods

 

Guess you like

Origin www.cnblogs.com/Fantac/p/11495039.html