反射

目錄python

反射

經過字符串來獲取,設置,刪除對象中的屬性或方法安全

  1. 用戶輸入一串字符串,執行該字符串對應的方法
  2. hasattr() :判斷一個屬性是否在對象中,返回true或者False
  3. getattr() :經過字符串獲取屬性和方法,若是獲取到了,就會返回相應的屬性和方法
  4. setattr():經過字符串來設置屬性和方法
  5. delatter():經過字符串來刪除屬性和方法
class Foo:
    def fun(self):
        print('run')
    def speak(self):
        print('speak')
p = Foo()

print(Foo.__dict__)#返回類的全部的方法{'__module__': '__main__', 'fun': <function Foo.fun at 0x0000014650AB7168>, 'speak': <function Foo.speak at 0x0000014650AB74C8>, '__dict__': <attribute '__dict__' of 'Foo' objects>, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__doc__': None}
cmd = input('請輸入命令')
# 方案一
# 執行類中的方法
print(Foo.__dict__[cmd])#方法的內存地址
Foo.__dict__[cmd](p)
# 方案二
# 執行類中的方法
if hasattr(p,cmd):#判斷一個屬性是否在對象中,返回true或者False
    run = getattr(p,cmd)#run方法的內存地址# 經過字符串獲取屬性和方法,若是獲取到了,就會返回相應的屬性和方法
    run()
else:
    print('沒有這個命令')
  1. setattr():經過字符串來設置屬性和方法code

    1. 放屬性對象

      class Foo:
          def fun(self):
              print('run')
          def speak(self):
              print('speak')
      p = Foo()
      # 經過用戶輸入key和value往對象中賦值
      key = input('請輸入key:')#qq
      value = input('請輸入value:')#123
      setattr(p,key,value)
      print(p.__dict__)
      #{'qq': '123'}
    2. 放方法內存

      class Foo:
          def fun(self):
              print('run')
          def speak(self):
              print('speak')
      p = Foo()
      # 動態的往對象裏面放方法
      def teat(a):
          print(a)
      print(p.__dict__)#{}
      
      setattr(p,'teat',teat)
      print(p.__dict__)#{'teat': <function teat at 0x000002968CC37168>}
      
      p.teat(11)#11
  2. delatter():經過字符串來刪除屬性和方法字符串

    1. 原始的刪除get

      class Foo:
          def fun(self):
              print('run')
          def speak(self):
              print('speak')
      p = Foo()
      # 原始的刪除
      p.name = 'czq'
      print(p.__dict__)#{'name': 'czq'}
      del p.name
      print(p.__dict__)#{}
    2. 動態刪除p中的屬性爲變量a的屬性input

      class Foo:
          def fun(self):
              print('run')
          def speak(self):
              print('speak')
      p = Foo()
      p.name = 'czq'
      p.age = 18
      p.sex = 'male'
      print(p.__dict__)#{'name': 'czq', 'age': 18, 'sex': 'male'}
      a = input('請輸入須要刪除的屬性:')#name
      delattr(p,a)
      print(p.__dict__)#{'age': 18, 'sex': 'male'}

用法

class BlackMedium:
    feature = 'Ugly'
    def __init__(self,name,addr):
        self.name = name
        self.addr = addr

    def sell_house(self):
        print('%s 黑中介賣房子啦,傻逼纔買呢,可是誰能證實本身不傻逼' % self.name)
    def rent_house(self):
        print('%s 黑中介租房子啦,傻逼才租呢' %self.name)
b1=BlackMedium('玉皇大帝','回龍觀')

# print(b1.__dict__)#對象的屬性,{'name': '玉皇大帝', 'addr': '回龍觀'}
# print(BlackMedium.__dict__)#類的方法,{'__module__': '__main__', 'feature': 'Ugly', '__init__': <function BlackMedium.__init__ at 0x0000012D3A3F7438>, 'sell_house': <function BlackMedium.sell_house at 0x0000012D3A3F7558>, 'rent_house': <function BlackMedium.rent_house at 0x0000012D3A3F75E8>, '__dict__': <attribute '__dict__' of 'BlackMedium' objects>, '__weakref__': <attribute '__weakref__' of 'BlackMedium' objects>, '__doc__': None}

方法一cmd

print(hasattr(b1,'sell_house'))#True,sell_house是對象的方法
a = 'sell_house'
getattr(b1,a)()#玉皇大帝 黑中介賣房子啦,傻逼纔買呢,可是誰能證實本身不傻逼

方法二it

sell_house = getattr(b1,a)
sell_house()#玉皇大帝 黑中介賣房子啦,傻逼纔買呢,可是誰能證實本身不傻逼
name = getattr(b1,'name')
print(name)#玉皇大帝

刪除屬性和方法

print(b1.__dict__)#{'name': '玉皇大帝', 'addr': '回龍觀'}

delattr(b1,'name')
print(b1.__dict__)#{'addr': '回龍觀'}

使用本身寫的模塊,經過反射來獲取模塊中是否有我要使用的屬性或方法,# 若是有就執行,沒有,就報錯

#utils.py

#別人寫的,領導規定要寫speak,run,eat方法
#這我的沒寫完
def speak():
    print('speak')


def run():
    print('run')
#這我的寫完了
def eat():
    print('eat')
import utils

utils.speak()
if hasattr(utils,'speak'):
    speak=getattr(utils,'speak')
    speak()

# 我覺得它寫完了
utils.eat()
# 更安全
if hasattr(utils,'eat'):
    eat=getattr(utils,'eat')
    eat()
else:
    print('那我的還沒寫完呢')
相關文章
相關標籤/搜索