当前位置: 移动技术网 > IT编程>脚本编程>Python > day 19 反射

day 19 反射

2018年12月25日  | 移动技术网IT编程  | 我要评论

救尔心胶囊,温瀛士,俞启威简历

1.isinstance, type, issubclass 的含义
isinstance:  判断你给对象时候是xxx类型的.(向上判断)
type: 返回xxx对象的数据类型
issubclass: 判断xxx类是否xxx的子类
class animal:
    def eat(self):
        print("刚睡醒吃点儿东西")
 
class cat(animal):
    def play(self):
        print("猫喜欢玩儿")
 
c = cat()
 
print(isinstance(c, cat)) # c是一只猫
print(isinstance(c, animal)) # 向上判断
 
a = animal()
print(isinstance(a, cat)) # 不能向下判断
 
print(type(a)) # 返回 a的数据类型
print(type([]))
print(type(c)) # 精准的告诉你这个对象的数据类型
 
# 判断.xx类是否是xxxx类的子类
print(issubclass(cat, animal))
print(issubclass(animal, cat))
def cul(a, b): # 此函数用来计算数字a和数字b的相加的结果
    # 判断传递进来的对象必须是数字. int float
    if (type(a) == int or type(a) == float) and (type(b) == int or type(b) == float):
        return a + b
    else:
        print("对不起. 您提供的数据无法进行计算")
 
print(cul(a, c))
2.如何区分方法和函数(代码)
  在类中:
         实例方法
               如果是类名.方法    == 是函数
               如果是对象.方法    == 是方法
from types import methodtype, functiontype
3.反射(重要)
attr: attribute
getattr()
      从xxx对象中获取xxx属性
hasattr()
      判断xxx队形中是否有xxx属性
delattr()
      从xxx对象中删除xxx属性
setattr()
      设置xxx对象中xxx属性为xxxx值
class person:
    def __init__(self, name, laopo):
        self.name = name
        self.laopo = laopo
 
 
p = person("宝宝", "林志玲")
 
print(hasattr(p, "laopo")) #
print(getattr(p, "laopo")) # p.laopo
 
setattr(p, "laopo", "胡一菲") # p.laopo = 胡一菲
setattr(p, "money", 100000000000) # p.money = 100000000
 
print(p.laopo)
print(p.money)
 
delattr(p, "laopo") # 把对象中的xxx属性移除.  != p.laopo = none
print(p.laopo)
 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网