反射

一.类型判断

1.isinstance

  isinstance(o,t)     判断o(object)是不是t(type)类型的(向上判断)

2.type

  type(o)     返回o 是什么数据类型

3.issubclass

  issubclass(a,b)     判断a是不是b类型的子类

class Animal:
    def eat(self):
        print("吃")

class Cat(Animal):
    def play(self):
        print("玩")

a = Animal()
c = Cat()

print(isinstance(c,Cat))# 判断c 是不是xxx类型
print(isinstance(c, Animal))   # 追溯到基类  父类

print(isinstance(a,Cat))    # 只能湘父类方向找  不能反向

print(type(c))     # 返回对象的数据类型

print(issubclass(Cat,Animal)) # 判断xxx是不是xxxx的一个子类

二.区分方法和函数

1.直接打印函数名

2.导入模块区分判断

from types import FunctionType ,MethodType

class Person:
    def chi(self):
        print("吃")

    @classmethod
    def he(cls):
        print("我是类方法")

    @staticmethod
    def wan():
        print("我是静态方法")

p = Person()
print(isinstance(p.chi,FunctionType))
print(isinstance(p.he,FunctionType))
print(isinstance(p.wan,FunctionType))

print(isinstance(Person.chi,MethodType))
print(isinstance(Person.he,MethodType))
print(isinstance(Person.wan,MethodType))

3.总结

  实例方法:

      如果使用    对象.实例方法        方法

      如果使用     类.实例方法   函数

  类方法:

      都是方法

  静态方法:

      都是函数

三.反射

1.从模块中拿东西去测试是否包含

import master   # 报错不用管
#
print("""
     1. chi:  大牛特别能吃
     2. he: 大牛特别能喝
     3. shui: 大牛特别能睡
     4. play: 大牛特别能玩儿
     5. sa: 大牛很喜欢撒谎
 """)
 while 1:
     content = input("请输入你要执行的函数:")
     if content == "1":
        master.chi()
     elif content == "2":
        master.he()
     elif content =="3":
         master.shui()
     elif content == "4":
         master.play_1()
     elif content == "5":
         master.sa()

2.反射,从测试中测是否包含

 while 1:
     content = input("请输入你要测试的功能:") # 用户输入的功能是一个字符串

     # 判断 xxx对象中是否包含了xxxxx
     if hasattr(master, content):
        xx = getattr(master, content)
         xx()
         print("有这个功能")
     else:
        print('没有这个功能')

3.发射函数

  1.getattr(a,b)      从a对象中获取到b属性值

  2.hasattr(a,b)      判断a对象中是否有b属性值

  3.delattr(a,b)  从a对象中删除b属性和对应的属性值

  4.setattr(a,b,c)  设置a对象中的b属性为c值

posted @ 2018-12-20 22:59  雾霾1024  阅读(170)  评论(0编辑  收藏  举报