zoukankan      html  css  js  c++  java
  • python------面向对象进阶反射详解(重点)

    一.反射

        通过字符串映射或者修改程序运行时的状态,属性,或者方法。

    1.getattr(object,name,default=None)

    2.hasattr(object,name)

    3.setattr(x,y,v)

    4.delattr(x,y)

     1 class Dog(object):
     2     def __init__(self,name):
     3         self.name = name
     4 
     5     def eat(self):
     6         print("%s is eating ..." % self.name)
     7 
     8 def bulk(self):   #不在类里
     9     print("%s is yelling.." %self.name)
    10 
    11 d = Dog("zhangsan")
    12 choice = input(">>:").strip()
    13 
    14 if hasattr(d,choice):  #判断一个对象里是否有对应的字符串的方法
    15     func = getattr(d,choice)   #根据字符串去获取对象里的对应的内存的方法
    16     func()
    17 else:
    18     # setattr(d,choice,bulk)   #is equivalent to 'x.y = v'  d.talk = bulk的
    19     # d.talk(d)
                                   #这样写就写死了,func  = getattr(d,choice)
    # func(d)
    20 21 setattr(d,choice,22) 22 a = getattr(d,choice) 23 print(a)

    >>:age
    22

     
  • 相关阅读:
    openVolumeMesh example 程序学习
    使用字符串创建java 对象
    HDU-1501-Zipper
    UVA-10285-Longest Run on a Snowboard
    HDU-2182-Frog
    HDU-2044-一只小蜜蜂
    POJ-1163-The Triangle
    HDU-1159-Common Subsequence
    HDU-2069-Coin Change
    HDU-4864-Task
  • 原文地址:https://www.cnblogs.com/bltstop/p/9745185.html
Copyright © 2011-2022 走看看