Python Learning Diary Reflection and several built-in functions

Keywords: Python Attribute

isinstance()

Determining whether obj in isinstance(obj,cls) is an object of CLS class

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

issubclass()

Determine if subclass in issubclass(sub,super) is a derived class of superclass

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

reflex

Reflection is the manipulation of variables with the name of a string type, everything in python is an object (reflection can be used)

1.hasattr()

The function is used to determine whether an object contains a corresponding property, usually in conjunction with getattr. hasattr is used first to determine if the object contains this property. If it does, it takes a value through getattr. If it does not, it prompts that there is no such 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('No such class attribute!')
#2
p = Person('Adson',1.6,75)
if hasattr(p,'bmi'):
    print(getattr(p,'bmi'))
else:
    print('No such property!')                #No such property!
#3
if hasattr(p,'fuc'):
    getattr(p,'fuc')()                   #weight...height...
else:
    print('No such method!')

2.getattr()

Function to return an object property value

(1) Properties of the reflected object

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

(2) Method of reflecting objects

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>>  Get the address of a binding method
ret()                       #This is fuc!   stay ret Call method with parentheses after

(3) Properties of the reflection class

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

(4) Method of reflection class (classmethod, staticmethod)

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'>>  Get a binding method
ret()                   #This is class fuc!
getattr(A,'fuc')()      #This is class fuc! Abbreviation

(5) Variables of the reflection module

Start by building a module with the module name pyfile.py and adding a variable

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

Then reflect the module's variables through my module

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

(6) Method of reflection module

Start by building a module named pyfile.py and adding a method

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

Then reflect the module method through my module

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

(7) Classes of reflection modules

import pyfile
b = getattr(pyfile,'B')('Josn')            #getattr Equivalent to having this module B Class and instantiated a b object
print(b.__dict__)                          #{'name': 'Josn'}
print(b.price)                             #200
b.fuc()                                    #This classB fuc..Josn

(8) Variables reflecting their own modules

Find the current module through sys.modules ['u main_']

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(ret)                                      #Mon Sep  9 22:39:05 2019

(9) Ways to reflect your own modules

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()

Used to set the value of an attribute that does not necessarily exist

class Person:
    age = 20
    def __init__(self,name,height,weight):
        self.name = name
        self.height = height
        self.weight = weight
#Modify an object
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'}
#Modify a class
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'}

The difference here is that objects and classes have different namespaces in which they store values

4.delattr()

Used to delete attributes

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

Posted by tmayder on Mon, 09 Sep 2019 09:42:23 -0700