python笔记(面向对象进阶:反射)

一、反射:getattr,hasattr

1、getattr()和hasattr():

    class Teacher:
        dic = {'查看学生信息':'','查看讲师信息':''}
        def show_student(self):
            print('show_student')
        def show_teacher(self):
            print('show_teacher')
        @classmethod
        def func(cls):
            print('哈哈哈哈')
    ret1 = getattr(Teacher,'dic')        #getattr()可执行字符串形式的属性
    ret2 = getattr(Teacher,'func')       #获取到函数的地址
    ret2()
    if hasattr(Teacher,'dic1'):          #hasattr:有字符串定义的方法或属性就返回TURE
        ret = getattr(Teacher,'dic1')
    print(ret1)

输出结果:

哈哈哈哈
{‘查看学生信息’: ‘’, ‘查看讲师信息’: ‘’}

class Teacher:
    dic = {'查看学生信息':'show_student','查看讲师信息':'show_teacher'}
    def show_student(self):
        print('student')
    def show_teacher(self):
        print('teacher')
    @classmethod
    def func(cls):
        print('哈哈哈哈')
long = Teacher()
key = input('输入需求:')
if hasattr(long,Teacher.dic[key]):          #hasattr:有字符串定义的方法或属性就返回TURE
    ret = getattr(long,Teacher.dic[key])
    ret()

输出结果:

输入需求:查看学生信息
student

2、通过反射对象名获取对象属性和普通方法:类名获取静态属性和类方法和静态方法
(1)普通方法self
(2)静态方法@staticmethod
(3)类方法@classmethod
(4)属性方法@property

@isinstance(obj,cls)检查obj是否是cls的对象

class A:pass
a = A()
print(isinstance(a,A))

输出结果:

True

@issubclass(sub,super)检查sub是否是super类的派生类(子类)
@反射:是用字符串类型的名字去操作变量

扫描二维码关注公众号,回复: 4212071 查看本文章

(5)反射对象的属性和方法

class B:
    name = 'xiaohai'
    age = 20
    def func(self):
        print('python')
b = B()
print(getattr(b,'name'))
ret = getattr(b,'func')
ret()

输出结果:

xiaohai
python

(6)反射类的属性和方法:classmethod,staticmethod

class C:
    name = 'xiaohai'
    age = 20
    @classmethod
    def func(cls):
        print('python')
print(getattr(C,'name'))
if hasattr(C,'func'):
    getattr(C,'func')()

输出结果:

xiaohai
python

(7)反射模块的属性和方法

import my_module  #自己定义的模块
print(getattr(my_module,'date'))

(8)反射自己模块中的变量

import sys
def wahaha():
    print('python')
year = 2018
getattr(sys.modules['__main__'],'wahaha')()
print(getattr(sys.modules['__main__'],'year'))

输出结果:

python
2018

(9)setattr():设置修改变量delattr():删除变量

class A:
    pass
a = A()
setattr(A,'name','alex')
setattr(a,'name','jing')
print(A.name)
print(a.name)
delattr(a,'name')
print(a.name)             #当对象中的属性被删除就在类的属性中找相同属性

输出结果:

alex
jing
alex

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_41433183/article/details/84433920