python Foundation (28):isinstance, issubclass, type, reflection

1. isinstance and issubclass

1.1 isinstance

isinstance(obj,cls) checks whether obj is a cls like object

class Foo(object):
  pass
  
obj = Foo()
  
isinstance(obj, Foo)

Example:

class Base(object):
  pass

class Foo(Base):
  pass

obj1 = Foo()
print(isinstance(obj1,Foo))  # Check that the first parameter (object) is an instance of the second parameter (class and parent).
print(isinstance(obj1,Base)) # Check that the first parameter (object) is an instance of the second parameter (class and parent).


obj2 = Base()
print(isinstance(obj2,Foo))  # Check that the first parameter (object) is an instance of the second parameter (class and parent).
print(isinstance(obj2,Base)) # Check that the first parameter (object) is an instance of the second parameter (class and parent).

1.2 issubclass

issubclass(sub, super) checks whether the sub class is a derived class of the super class

class Foo(object):
  pass
 
class Bar(Foo):
  pass
 
issubclass(Bar, Foo)

Example:

class Base(object):
  pass

class Foo(Base):
  pass

class Bar(Foo):
  pass

print(issubclass(Bar,Base)) # Check if the first parameter is a descendant of the second parameter

2. type

Gets which class the current object is created by.

class Foo(object):
    pass

obj = Foo()

print(obj,type(obj)) # Gets which class the current object was created by.
if type(obj) == Foo:
    print('obj yes Foo type')

Example:

class Foo(object):
    pass

class Bar(object):
    pass

def func(*args):
    foo_counter =0
    bar_counter =0
    for item in args:
        if type(item) == Foo:
            foo_counter += 1
        elif type(item) == Bar:
            bar_counter += 1
    return foo_counter,bar_counter

# result = func(Foo(),Bar(),Foo())
# print(result)

v1,v2 = func(Foo(),Bar(),Foo())
print(v1,v2)

3. reflection

3.1 what is reflection

The concept of reflection was first proposed by Smith in 1982. It mainly refers to the ability of a program to access, detect and modify its own state or behavior (introspection). The introduction of this concept soon led to the research on application reflection in the field of computer science. It was first adopted in the field of programming language design, and has made achievements in Lisp and object-oriented.  

3.2 reflection in Python

Reflection in python object-oriented: manipulating object related properties in the form of strings. Everything in python is an object (you can use reflection).

Four functions for introspection:

hasattr:

def hasattr(*args, **kwargs): # real signature unknown
    """
    Return whether the object has an attribute with the given name.
    
    This is done by calling getattr(obj, name) and catching AttributeError.
    """
    pass

getattr:

def getattr(object, name, default=None): # known special case of getattr
    """
    getattr(object, name[, default]) -> value
    
    Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
    When a default argument is given, it is returned when the attribute doesn't
    exist; without it, an exception is raised in that case.
    """
    pass

setattr:

def setattr(x, y, v): # real signature unknown; restored from __doc__
    """
    Sets the named attribute on the given object to the specified value.
    
    setattr(x, 'y', v) is equivalent to ``x.y = v''
    """
    pass

delattr:

def delattr(x, y): # real signature unknown; restored from __doc__
    """
    Deletes the named attribute from the given object.
    
    delattr(x, 'y') is equivalent to ``del x.y''
    """
    pass

Examples of four methods:

class Foo:
    f = 'Static variable of class'
    def __init__(self,name,age):
        self.name=name
        self.age=age

    def say_hi(self):
        print('hi,%s'%self.name)

obj=Foo('egon',73)

#Check whether there is a property
print(hasattr(obj,'name'))
print(hasattr(obj,'say_hi'))

#get attribute
n=getattr(obj,'name')
print(n)
func=getattr(obj,'say_hi')
func()

print(getattr(obj,'aaaaaaaa','It doesn't exist.')) #Report errors

#set a property
setattr(obj,'sb',True)
setattr(obj,'show_name',lambda self:self.name+'sb')
print(obj.__dict__)
print(obj.show_name(obj))

#Delete attribute
delattr(obj,'age')
delattr(obj,'show_name')
delattr(obj,'show_name111')#Non-existent,False report

print(obj.__dict__)

These four methods apply to classes and objects (everything is an object, and the class itself is an object)

Class is also an object:

class Foo(object):
 
    staticField = "old boy"
 
    def __init__(self):
        self.name = 'wupeiqi'
 
    def func(self):
        return 'func'
 
    @staticmethod
    def bar():
        return 'bar'
 
print getattr(Foo, 'staticField')
print getattr(Foo, 'func')
print getattr(Foo, 'bar')

Reflect current module members:

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import sys


def s1():
    print 's1'


def s2():
    print 's2'


this_module = sys.modules[__name__]

hasattr(this_module, 's1')
getattr(this_module, 's2')

Import other modules and use reflection to find out whether there is a method in the module.

module_test.py:

# -*- coding:utf-8 -*-

def test():
    print('from the test')

index.py:

# -*- coding:utf-8 -*-
 
"""
//Program directory:
    module_test.py
    index.py
"""

import module_test as obj

#obj.test()

print(hasattr(obj,'test'))

getattr(obj,'test')()

Keywords: Python Attribute Programming Lambda

Added by lordrain11 on Fri, 15 Nov 2019 22:40:07 +0200