第二十七天反射和面向对像中的内置函数

1.isinstance判断类和对象之间的关系如果存在类对象关系返回True否则返回False

class Person:
    def func(self):
        pass
a=Person()
b=1
print(isinstance(a,Person)) #左边对象右边类
print(isinstance(b,Person))
结果为
True
False
View Code

2。issubclass判断是否是子类和父类之间的关系:

class Person:
    def func(self):
        pass
class Son(Person):
    pass
b=Person()
print(issubclass(Son,Person)) #左边子类右边父类(超类、基类)
结果为
True
View Code

3.反射就是用字符串形式的名字去操作变量进行操作:

  3.1我们前面也学过用字符串进行变量的操作:

name=123
print(eval('name'))
结果为
123
View Code

使用这个存在安全隐患:因为这种操作是得到别人写好的代码直接执行,你也不知道别人的代码是否有代码病毒。

  3.2使用反射可以解决这一个问题,使用反射式使用一段写好的代码,然后执行里面的属性和方法。

4.反射类里面的属性

class Person:
    def func(self):
        print('哈哈哈')
a=Person()#实例化
a.name='alex'#给对象中添加一个元素
Person.name='123'
ret=getattr(a,'name')
print(ret)
print(a.__dict__)#显示对象中所有的属性信息并以字典的形式返回
print(Person.__dict__)
结果为
alex
{'name': 'alex'}
{'__module__': '__main__', 'func': <function Person.func at 0x0000024D5EFF5730>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None, 'name': '123'}
View Code

5.反射使用类里面的方法:

class Person:
    def func(self):
        print('哈哈哈')
a=Person()#实例化
a.name='alex'#给对象中添加一个元素
ret=getattr(a,'func')  #这一步得到方法的地址(和函数差不多)
ret()
结果为
哈哈哈
View Code

6那么反射有什么用:简单小例子用户通过输入想要查看某个对象的属性:

class Person:
    def func(self):
        print('哈哈哈')
a=Person()#实例化
a.name='alex'#给对象中添加一个元素
a.age=16
name=input('输入你想查看的属性;')
ret=getattr(a,name)
print(ret)
结果为
输入你想查看的属性;name
alex
View Code

  还有一种方法也是可以通过字符串得到类中的属性:

class Person:
    def func(self):
        print('哈哈哈')
a=Person()#实例化
a.name='alex'#给对象中添加一个元素
a.age=16
name=input('输入你想查看的属性;')
ret=a.__dict__[name]
print(ret)
结果为
输入你想查看的属性;name
alex
View Code

7但是这种方法没有办法得到类中的方法,还是只能使用反射:

class Person:
    __key=123
    @staticmethod
    def func():
        print('哈哈哈')
    @classmethod
    def func1(cls):
       return cls.__key

a=Person()#实例化
a.name='alex'#给对象中添加一个元素
a.age=16
name=input('输入你像调用的方法;')
ret=getattr(Person,name)
ret()
结果为
输入你像调用的方法;func
哈哈哈
View Code

  还有一中使用反射得到方法的使用方法:

class Person:
    __key=123
    @staticmethod
    def func():
        print('哈哈哈')
    @classmethod
    def func1(cls):
       return cls.__key

a=Person()#实例化
a.name='alex'#给对象中添加一个元素
a.age=16
name=input('输入你像调用的方法;')
print(getattr(Person,name)())
结果为
输入你像调用的方法;func1
123
View Code

8.模块里的反射方法:

import mile  #调用mile模块
print(getattr(mile,'day'))  #使用模块中day的属性
结果为
123
View Code

9.调用模块中的方法:

import mile  #调用mile模块
print(getattr(mile,'day'))  #使用模块中day的属性
getattr(mile,'func')()  #调用模块中func方法
结果为
123
哇哈哈
View Code

10内置模块也可以使用反射方法:

import time
print((getattr(time,'time'))())
结果为
1582943294.4412374
View Code

11.为什么random就不能使用getattr

import random
print(getattr(random,'randint(1,10))'))
结果为
Traceback (most recent call last):
  File "D:/python练习程序/第二十七天/practise.py", line 48, in <module>
    print(getattr(random,'randint(1,10))'))
AttributeError: module 'random' has no attribute 'randint(1,10))
View Code
import  random
print(getattr(random,'randint')(1,10))
结果为
6
View Code

12.那么python中是否可以反射自己的模块:

year=2020
import sys
name=input('请输入>>>')
print(getattr(sys.modules[__name__],name))

结果为
请输入>>>year
2020
View Code

13要反射函数怎么办:

import time
print(time.strftime('%Y-%m-%d %H:%M:%S'))
print(getattr(time,'strftime')('%Y-%m-%d %H:%M:%S'))
结果为
2020-02-29 10:49:45
2020-02-29 10:49:45
View Code

14.有时候我在在使用getattr时如果没有会报错:

import time
getattr(time,'fjdfj')
结果为
Traceback (most recent call last):
  File "D:/python练习程序/第二十七天/practise.py", line 55, in <module>
    getattr(time,'fjdfj')
AttributeError: module 'time' has no attribute 'fjdfj'
View Code

  怎么解决报错的问题:

import time
if hasattr(time,'fjdfj'): #如果为真执行下面如果为假不执行
    getattr(time,'fjdfj')#两个括号里要写的一致
else:
    print('上面的指令有误')
结果为
上面的指令有误
View Code

15对类的变量进行设置修改:

class A:
    def func(self):
        print('修改成功')
a=A()
a.name='alex'
print(a.name)
print(a.func())
setattr(a,'name','subin') #对属性进行修改
print(a.name)
setattr(a,'func','func1') #无法对方法进行修改
print(a.func1())
结果为
  File "D:/python练习程序/第二十七天/practise.py", line 69, in <module>
alex
    print(a.func1())
AttributeError: 'A' object has no attribute 'func1'
修改成功
None
subin
View Code
class A:
    def func(self):
        print('修改成功')
a=A()
a.name='alex'
print(a.name)
print(a.func())
delattr(a,'name') #对属性进行修改
print(a.name)

结果为
Traceback (most recent call last):
  File "D:/python练习程序/第二十七天/practise.py", line 78, in <module>
    print(a.name)
AttributeError: 'A' object has no attribute 'name'
alex
修改成功
None
View Code

猜你喜欢

转载自www.cnblogs.com/ab461087603/p/12381954.html