我想在python中创建一个类,它应该像这样工作:
a = exampleclass(data)
或仅exampleclass(data)
)第3部分是我有问题的部分。我如何真正改变类(class)内部的类(class)?例如:
如果我有两个类,一个是
Small_Numbers
,另一个是Big_numbers
;现在我希望将小于1000的small_number
转换为Big_number
,反之亦然,即testcode:a = Small_number(50)
type(a) # should return Small_number.
b = Small_number(234234)
type(b) # should return Big_number.
c = Big_number(2)
type(c) # should return Small_number.
这可能吗?
最佳答案
使用factory method是解决此问题的常用方法,尤其是因为实例化一个类与在Python中调用一个函数没有区别。
但是,如果您确实需要,可以将其分配给self.__class__
:
THRESHOLD = 1000
class Small(object):
def __init__(self, n):
if n < THRESHOLD:
self.n = n
else:
self.__class__ = Big
self.__init__(n)
class Big(object):
def __init__(self, n):
if n < THRESHOLD:
self.__class__ = Small
self.__init__(n)
else:
self.n = n
这可以按预期工作:
>>> a = Small(100)
>>> type(a)
<class 'Small'>
>>> b = Small(1234)
>>> type(b)
<class 'Big'>
>>> c = Big(2)
>>> type(c)
<class 'Small'>
如果分配给
self.__class__
似乎太奇怪了,请改为you can override __new__
。在调用__init__
之前调用此方法,并且可以使用该方法来选择要实例化的类:THRESHOLD = 1000
class Switcher(object):
def __new__(cls, n):
if n < THRESHOLD:
new_cls = Small
else:
new_cls = Big
instance = super(Switcher, new_cls).__new__(new_cls, n)
if new_cls != cls:
instance.__init__(n)
return instance
class Small(Switcher):
def __init__(self, n):
self.n = n
class Big(Switcher):
def __init__(self, n):
self.n = n