Python basis (nine) - Object-Oriented two

一、isinstance(obj,cls)和issubclass(sub,super)

1.1、isinstance(obj,cls) 

Whether isinstance (obj, cls) checks whether obj is the object of the class cls

class Foo(object):
    pass

obj = Foo()
print(isinstance(obj,Foo))  #True

1.2、issubclass(sub, super)

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

class Foo(object):
    pass

class Bar(Foo):
    pass

print(issubclass(Bar,Foo))  #True

Second, reflection

Four function can be achieved self-examination for classes and objects (everything is an object, the class itself is a target)

2.1、hasattr(object,name)

There is no method of determining object name string corresponding to a property or

2.2、getattr(object, name, default=None)

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

getattr(object, name, default=None)

2.3、setattr(x, y, v)

Setting Properties

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

setattr(x, y, v)

2.4、delattr(x, y)

Delete property

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

delattr(x, y)

2.5 Example

1) Example a

BlackMedium class: 
    Feature = "Ugly" 
    DEF the __init __ (Self, name, addr): 
        the self.name name = 
        self.addr addr = 

    DEF sell_house (Self): 
        Print ( "% S black intermediary sell the house it"% self.name) 

    rent_house DEF (Self): 
        Print ( "% S black intermediary rent it" the self.name%) 

BlackMedium ( "Man Shing land", "open days Park") = B1 

# detect whether it contains a property 
print (hasattr (b1, "name")) #True 
Print (the hasattr (B1, "sell_house")) # as a string or NameError: name 'sell_house' iS Not defined 
#Print (the hasattr (B1, rent_house)) #NameError: name ' sell_house 'IS Not defined 

# properties acquired 
print (getattr (b1, "name ")) # Wan into opposite ==> attribute data acquired 
func = getattr (b1, "rent_house ") # get the function attributes 
func () # Wan Cheng Landmark black intermediary to rent it

# Getattr (b1, "abc" ) # AttributeError when given attribute does not exist: 'BlackMedium' Object attribute has NO 'ABC' 
Print (getattr (B1, "ABC", "absent")) == absence #> when using getattr acquiring attribute when the attribute is not present, you can specify a default return value 

# set properties 
setattr (b1, "sb", "True") # set data attribute 
print (b1 .__ dict__) # { 'name': ' Wan as opposed to ',' addr ':' open days Park ',' SB ':' True '} 

setattr (B1, "SHOW_NAME", the lambda Self: the self.name + "_ SB") # set function attributes 
print (b1 .__ dict__) # { 'sb': 'True ', 'name': ' Wan opposite to', 'show_name': <function <lambda> at 0x000001B354757F28>, 'addr': ' Park open days'} 
Print (b1.show_name (B1 land)) # Wan into _sb 

# deleted property 
print (b1 .__ dict__) # { 'name': 'Wancheng Land ',' sb ':' True ',' addr ':' open days Park ',' SHOW_NAME ': <function <the lambda> AT 0x0000029A9F8D7F28>} 
delattr (B1, "addr") 
delattr (B1, "SHOW_NAME ")
# Delattr (b1, "show_name123" ) #AttributeError: show_name123 property being given the absence 
print (b1 .__ dict__) # { 'sb': 'True', 'name': ' ten thousand to opposite'}

2) Example Two

class Foo(object):
    staticField = "oldboy"

    def __init__(self):
        self.name = name

    def func(self):
        return "func"

    @staticmethod
    def bar():
        return "bar"

print(getattr(Foo,"staticField"))  #oldboy
print(getattr(Foo,"func"))  #<function Foo.func at 0x00000237B782E378>
print(getattr(Foo,"bar"))   #<function Foo.bar at 0x00000228D871E400>

3) Example Three

View module itself

import sys

def s1():
    print("s1")

def s2():
    print("s2")

this_module = sys.modules[__name__]
print(this_module)  #<module '__main__' from 'G:/python/反射.py'> ==> __main__表示当前模块

print(hasattr(this_module,"s1"))  #True
print(getattr(this_module,"s2"))  #<function s2 at 0x000001B74743E378>

4) Example Four

Import other modules, the module using the reflection see the existence of a method

image

module_test.py:

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

index.py:

import aaa.module_test as obj

obj.test()   #from the test

print(obj)   #<module 'aaa.module_test' from 'G:\\python\\aaa\\module_test.py'>
print(hasattr(obj,'test'))  #True
print(getattr(obj,"test"))  #<function test at 0x0000024770C3E400>返回函数地址
getattr(obj,'test')()   #from the test

Guess you like

Origin www.cnblogs.com/hujinzhong/p/11484620.html