首页 > 其他分享 >蛇院自习室

蛇院自习室

时间:2022-08-25 17:36:10浏览次数:34  
标签:__ attr self wallet 蛇院 property 自习室 def

  • defaultdict 学习pytorch的时候接触到了这个包,总结一下自己的理解


    drawing

    from collections import defaultdict
    
    class Person():
        def __init__(self):
            self.name = 'Tom'
            self.age = 20
            self.wallet = defaultdict(Wallet)
            self.property = defaultdict(Property)
    
        def add_wallet(self, key, val):
            self.wallet[key] = val
    
        def add_property(self, key, val):
            self.property[key] = val
    
        def __getattr__(self, attr):
            if attr in self.wallet:
                return self.wallet[attr]
            elif attr in self.property:
                return self.property[attr]
            elif attr in self.__dict__:
                return self.__dict__[attr]
            else:
                raise AttributeError('该item不存在,查询出错!')
    
      class Wallet():
        def __init__(self):
            pass
    
      class Property():
          def __init__(self):
              pass
    
      p = Person()
      print(p.name)   # Tom
      p.add_wallet('RMB', 1000)
      print(p.RMB)    # 1000
      p.add_property('house', 2)
      print(p.house)  # 2
    
    

标签:__,attr,self,wallet,蛇院,property,自习室,def
From: https://www.cnblogs.com/wjw-cat/p/16624856.html

相关文章