zoukankan      html  css  js  c++  java
  • day17-反射

    #反射最常用的两个方法:hasattr getattr
    # 1. 反射对象属性,反射对象方法:
    class Goods:
        def __init__(self,name):
            self.name = name
        def price(self):
            print('{}的价格是8元'.format(self.name))
    apple = Goods('apple')
    ret = getattr(apple,'name') #属性使用字符串的形式书写。反射对象属性。
    print(ret)  #apple ,打印属性值
    ret1 = getattr(apple,'price') #方法也是使用字符串的形式书写。反射对象的方法。
    ret1()     #apple的价格是8元 ,方法调用
    
    # 2. hasattr
    class Goods:
        def __init__(self,name):
            self.name = name
    g = Goods('apple')
    if hasattr(g,'name'): #如果对象有name属性
        ret = getattr(g,'name') #反射(获取)对象属性
        print(ret) #apple
    
    # 3. 反射类属性,反射类方法:
    class Goods:
        discount = 0.8
        @classmethod
        def price(cls):
            print('苹果的价格是10元')
    ret1 = getattr(Goods,'discount')
    print(ret1)
    ret = getattr(Goods,'price')
    ret()
    
    # 4. 反射模块属性,模块方法
    import model
    ret = getattr(model,'name')
    print(ret) #apple
    ret1 = getattr(model,'price')
    ret1() #apple的价格是8元
    #model.py的代码是:
    # name = 'apple'
    #def price():
    #    print('{}的价格是8元'.format(name))
    
    #5. 反射可以简化代码:
    class Goods:
        def __init__(self,name,price):
            self.name = name
            self.price = price
    g = Goods('apple',8)
    属性名 = input('请输入要查找的内容:')
    if 属性名 == 'name':
        ret = getattr(g,属性名)
        print(ret)
    elif 属性名 == 'price':
        ret = getattr(g,属性名)
        print(ret)
    else:
        print('没找到此内容')
    
    class Goods:
        def __init__(self,name,price):
            self.name = name
            self.price = price
    g = Goods('apple',8)
    属性名 = input('请输入要查找的内容:') #请输入要查找的内容:name
    ret = getattr(g,属性名)
    print(ret)#apple
  • 相关阅读:
    判断窗体 show完成
    【洛谷1349】广义斐波那契数列
    【洛谷2744 】【CJOJ1804】[USACO5.3]量取牛奶Milk Measuring
    【洛谷T7153】(考试) 中位数
    【洛谷T7152】(考试题目)细胞
    【洛谷1962】 斐波那契数列
    【洛谷1855】 榨取kkksc03
    【HDU2255】奔小康赚大钱
    【洛谷1402】酒店之王
    【洛谷1607】【USACO09FEB】庙会班车
  • 原文地址:https://www.cnblogs.com/python-daxiong/p/11239030.html
Copyright © 2011-2022 走看看