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
  • 相关阅读:
    CentOS7 彻底关闭 IPV6
    查看 nodejs 安装包的相关指令
    npm 查看全局安装过的包
    更换 nodejs npm 镜像为 淘宝 镜像
    更改 Centos 6 的 yum 源
    Nodejs 实现 WebSocket 太容易了吧!!
    解决国内 NPM 安装依赖速度慢问题
    详解 HTML5 中的 WebSocket 及实例代码-做弹幕
    JSmpeg-用JavaScript编写的视频播放器
    适用于Centos6.x系统的15项优化脚本
  • 原文地址:https://www.cnblogs.com/python-daxiong/p/11239030.html
Copyright © 2011-2022 走看看