• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

wjw-cat

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

蛇院自习室

  • 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
    
    
  • python编程范式

    两种思路:
    1> 面向对象
    把大问题逐步拆分为小问题,从上到下;
    2> 面向过程

posted on 2022-08-25 17:20  小王爱烧烤  阅读(17)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3