【发布时间】: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
有什么好的理由可以将一个类分配给一个变量,如下面的代码所示?由于该机制,人们可以做哪些有用/有趣的事情?
class foo:
# Some initialization stuff
def __init__(self):
self.x = 0
# Some methods and other stuff
myVar = foo
【问题讨论】:
标签: python
我在生产代码中最常看到的情况是依赖注入或“编译时”配置。
例如,我可能有一些实现某些策略或命令的类,但我还没有构造函数的详细信息。
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)] 上的循环不依赖于任何特定类型,因此与类型列表的内容解耦。
【讨论】:
一个重要的用例当然是类型检查或过滤:
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
【讨论】:
有很多可能性。一种可能是您有多个类,并且您想从所有类中访问相同的属性。
例如:
classes = [Class1, Class2, Class3]
for c in classes:
print(c.__dict__)
【讨论】:
我能想到的唯一可能的原因是您将多次调用构造函数。所以,而不是
x1 = foo()
x2 = foo()
x3 = foo()
你可以写
cls = foo
x1 = cls()
x2 = cls()
x3 = cls()
因此,您只能将cls=foo 更改为cls=bar,其余无需更改。
但是,这仅适用于代码 sn-ps,只是为了快速尝试。如果您确实需要多次执行某项操作,请编写一个函数。
【讨论】: