Python面向对象之-反射

一: 概述

Python中一切皆对象,在Python中的反射:通过字符串的形式操作对象的属性或者方法

  • hasattr  判断是对象否有改属性或者方法,有就返回True,没有就返回false
  • getattr  如果是属性获得该属性的值,如果是方法获得该方法的内存地址

 

二: 在模块中使用反射

两个文件,main,py,start,py 即Python的模块

mian.py文件内容如下

def func1():
    print('func1')

def func2():
    print('func2')

 

start.py文件内容如下

print(hasattr(main,'func1'))
print(hasattr(main,'func2'))
print(hasattr(main,'func3'))

 

执行如果如下

True
True
False

三: Python 面向对象中使用反射

class Person:
    role = 'person'
    def __init__(self,name):
        self.name = name

    def walk(self):
        print("%s is walking"%self.name)

wangys = Person('wangys')

print(hasattr(wangys,'role'))
print(hasattr(wangys,'name'))
print(hasattr(wangys,'walk'))
print(hasattr(wangys,'eat'))
True
True
True
False

print(getattr(wangys,'role'))
print(getattr(wangys,'name'))
print(getattr(wangys,'walk'))
getattr(wangys,'walk')()

person
wangys
<bound method Person.walk of <__main__.Person object at 0x00000216037DDA90>>
wangys is walking

 

通常hasattr跟getattr结合使用

class Person:
    role = 'person'
    def __init__(self,name):
        self.name = name

    def walk(self):
        print("%s is walking"%self.name)

wangys = Person('wangys')

if  hasattr(wangys,'role'):
    print(getattr(wangys,'role'))

if hasattr(wangys,'walk'):
    getattr(wangys,'walk')()

if hasattr(wangys,'eat'):
    getattr(wangys,'eat')()
else:
    print('没有改方法')

person
wangys is walking
没有改方法

 

posted @ 2019-02-17 17:25  择一事,终一生  阅读(351)  评论(0编辑  收藏  举报