python 面向对象(四)反射

####################总结##########

1.

isinstance: 判断xxx是否是xxx类型的(向上判断) 
type: 返回xx对象的数据类型
issubclass: 判断xxx类是否是xxx类的子类

isinstance: 判断xxx是否是xxx类型的(向上判断)

class Animal:
    pass
class Cat(Animal):
    pass
class BoSiCat(Cat):
    pass
print(issubclass(Cat, Animal)) # 判断第一个参数是否是第二个参数的后代
print(issubclass(Animal, Cat))
print(issubclass(BoSiCat, Animal)) # True

##########结果

True
False
True

type: 返回xx对象的数据类型

def add(a, b):
    if (type(a) == int or type(a) == float) and (type(b) == int or type(b) == float):
        return a + b
    else:
        print("算不了")

print(add("胡汉三", 2.5))

issubclass: 判断xxx类是否是xxx类的子类

class Animal:
    pass
class Cat(Animal):
    pass
class BoSiCat(Cat):
    pass
print(issubclass(Cat, Animal)) # 判断第一个参数是否是第二个参数的后代
print(issubclass(Animal, Cat))
print(issubclass(BoSiCat, Animal)) # True

#结果
True
False
True

2.

区分函数和方法

#方法一

def
func(): print("我是函数") class Foo: def chi(self): print("我是吃") # print(func) # <function func at 0x0000000001D42E18> f = Foo() # f.chi() print(f.chi) # <bound method Foo.chi of <__main__.Foo object at 0x0000000002894A90>> # 野路子: 打印的结果中包含了function. 函数 # method . 方法
#方法二
from collections import Iterable, Iterator # 迭代器
from
types import FunctionType, MethodType # 方法和函数 class Person: def chi(self): # 实例方法 print("我要吃鱼") @classmethod def he(cls): print("我是类方法") @staticmethod def pi(): print("泥溪镇地皮")
p
= Person() print(isinstance(Person.chi, FunctionType)) # True print(isinstance(p.chi, MethodType)) # True

 3.反射

1. hasattr(对象, str) 判断对象中是否包含str属性
2. getattr(对象, str) 从对象中获取到str属性的值
3. setattr(对象, str, value) 把对象中的str属性设置为value
4. delattr(对象, str) 把str属性从对象中删除

class Person:
    def __init__(self,name,laopo):
        self.name=name
        self.laopo=laopo
p= Person('宝宝','林志玲')

print(hasattr(p,'laopo'))
print(getattr(p,'laopo'))
setattr(p,'laopo','胡一菲')
setattr(p,'money',1000)

print(p.laopo)
print(p.money)
delattr(p, "laopo") # 把对象中的xxx属性移除.  != p.laopo = None
print(p.laopo)

########结果
True
林志玲
胡一菲
1000

Traceback (most recent call last):
File "D:/python_work_s18/day18关系/test.py", line 87, in <module>
print(p.laopo)
AttributeError: 'Person' object has no attribute 'laopo'

Process finished with exit code 1

实例二  

####单独文件master
def chi():
    print("大牛很能吃")

def he():
    print("大牛一次喝一桶")

def shui():
    print("大牛一次睡一年")

def play_1():
    print("大牛不玩儿压缩了. 玩儿儿童节")

def sa():
    print("大牛很能撒谎")

def la():
    print("大牛喜欢拉二胡")
while 1:
    content = input("请输入你要测试的功能:") # 用户输入的功能是一个字符串

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

猜你喜欢

转载自www.cnblogs.com/zaizai1573/p/10159526.html