zoukankan      html  css  js  c++  java
  • day 19 反射

    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)
     
  • 相关阅读:
    二级菜单
    eclipse高版本中EasyExplore的替换插件OpenExplore
    Python学习一
    原型编程的基本规则
    【CF671D】 Roads in Yusland(对偶问题,左偏树)
    【洛谷4542】 [ZJOI2011]营救皮卡丘(最小费用最大流)
    【洛谷4313】 文理分科(最小割)
    【洛谷4001】 [ICPC-Beijing 2006]狼抓兔子(最小割)
    【洛谷2057】 [SHOI2007]善意的投票(最小割)
    【洛谷2053】 [SCOI2007]修车(费用流)
  • 原文地址:https://www.cnblogs.com/yanghongtao/p/10169864.html
Copyright © 2011-2022 走看看