0

我会在 Python 中这样做:

result = SomeClass(some_argument)

不过,这就是问题所在。我不希望结果是一个实例,而是一个不可变对象(例如 int)。基本上,一个类的空洞角色是返回一个从参数计算出来的值。我正在使用一个类而不是一个用于 DRY 目的的函数。由于上面的代码不起作用,因为它总是返回 SomeClass 的一个实例,最好的选择是什么?

我唯一的想法是有一个静态方法,但我不喜欢它:

result = SomeClass.static_method(some_argument)
4

2 回答 2

3

您可以覆盖__new__. 虽然这很少是一个好主意和/或必要的......

>>> class Foo(object):
...     def __new__(cls):
...         return 1
... 
>>> Foo()
1
>>> type(Foo())
<type 'int'>

如果您不返回 , 的实例cls__init__则永远不会被调用。

于 2013-05-19T20:24:50.497 回答
0

如果您有工厂方法,基本上类方法就是要走的路。关于结果 - 这实际上取决于您寻求什么样的不变性,但基本上 namedtuple 在封装事物方面做得很好并且也是不可变的(就像普通元组一样):

from collections import namedtuple
class FactoryClass(object):
     _result_type = namedtuple('ProductClass', ['prod', 'sum'])
     @classmethod
     def make_object(cls, arg1, arg2):
         return cls._result_type(prod=arg1 * arg2, sum=arg1 + arg2)

>>> FactoryClass.make_object(2,3)
ProductClass(prod=6, sum=5)
>>> x = _
>>> x.prod = 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
于 2013-05-19T20:47:32.217 回答