【问题标题】:Uses of assigning a class to a variable in Python在 Python 中将类分配给变量的用途
【发布时间】:2019-07-21 11:13:51
【问题描述】:

有什么好的理由可以将一个类分配给一个变量,如下面的代码所示?由于该机制,人们可以做哪些有用/有趣的事情?

class foo:

    # Some initialization stuff
    def __init__(self):
        self.x = 0

    # Some methods and other stuff

myVar = foo

【问题讨论】:

    标签: python


    【解决方案1】:

    我在生产代码中最常看到的情况是依赖注入或“编译时”配置。

    例如,我可能有一些实现某些策略或命令的类,但我还没有构造函数的详细信息。

    class StrategyOne:...
    class StrategyTwo:...
    
    def my_func(vars, Strategy):
        x = some_calculation(vars)
        st = Strategy(x)
    

    django-rest-framework docs 中可以看到使用此配置的示例

    class AccountSerializer(serializers.ModelSerializer):
        class Meta:
            model = Account
            fields = ('id', 'account_name', 'users', 'created')
    

    我认为大多数用例都属于“我不想耦合到这个特定的类”的原则。 Another level of indirection and all.

    type checking example 为例。类型集合[x for x in lst if isinstance(x, types)] 上的循环不依赖于任何特定类型,因此与类型列表的内容解耦。

    【讨论】:

      【解决方案2】:

      一个重要的用例当然是类型检查或过滤:

      class Foo:
          pass
      
      lst = ["bla", 42, Foo()]
      types = (str, Foo)
      filtered = [x for x in lst if isinstance(x, types)]
      # ['bla', <__main__.Foo at 0x7fa3422aa668>]
      

      另一个可能是动态创建某些类的实例,例如defaultdict

      class Bar:
          def __init__(self):
              self.value = 0
      
      from collections import defaultdict
      d = defaultdict(Bar)
      for x, y in [(1,1), (1,2), (2,3), (2,4)]:
          d[x].value += y
      print(d[1].value) # 3
      

      【讨论】:

        【解决方案3】:

        有很多可能性。一种可能是您有多个类,并且您想从所有类中访问相同的属性。

        例如:

        classes = [Class1, Class2, Class3]
        
        for c in classes:
            print(c.__dict__)
        

        【讨论】:

          【解决方案4】:

          我能想到的唯一可能的原因是您将多次调用构造函数。所以,而不是

          x1 = foo()
          x2 = foo()
          x3 = foo()
          

          你可以写

          cls = foo
          x1 = cls()
          x2 = cls()
          x3 = cls()
          

          因此,您只能将cls=foo 更改为cls=bar,其余无需更改。

          但是,这仅适用于代码 sn-ps,只是为了快速尝试。如果您确实需要多次执行某项操作,请编写一个函数。

          【讨论】:

            猜你喜欢
            • 2021-12-02
            • 1970-01-01
            • 2021-09-20
            • 1970-01-01
            • 1970-01-01
            • 2012-05-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多