有没有办法改变CLASS OBJECT以便type(object)
报告自定义字符串?
class MyClass(object):
def __init__(self, t):
if 'detector' in t:
my_type_string = "I am set as a detector."
else:
my_type_string = "I am set as a broadcaster."
>>> o = MyClass('detector')
>>> type(o)
I am set as a detector.
答案 0 :(得分:6)
你不应该这样做。相反,您应该实现两个单独的类,这两个类都继承自MyClass
:
class MyClass(object):
my_type_string = "I am not set to anything."
def __str__(self):
return self.my_type_string
class Detector(MyClass):
my_type_string = "I am set as a detector."
class Broadcaster(MyClass):
my_type_string = "I am set as a broadcaster."
>>> o = Detector()
>>> type(o)
__main__.Detector
>>> str(o)
'I am set as a detector.'
如果你想根据你提供的字符串切换你的类,你可以实现一个返回所需对象的工厂:
def factory(t):
if 'detector' in t:
return Detector()
else:
return Broadcaster()
>>> o = factory('detector')
>>> type(o)
__main__.Detector
答案 1 :(得分:1)
你可以,但这很危险。 type
是内置的,其他地方可以使用它。但是如果你知道自己在做什么以及为什么要这样做,你可以重新定义type
。但这里是龙。你已被警告过。:
class MyClass(object):
def __init__(self, t):
if 'detector' in t:
self.my_type_string = "I am set as a detector."
else:
self.my_type_string = "I am set as a broadcaster."
def type(obj):
return obj.my_type_string if isinstance(obj, MyClass) else __builtins__.type(obj)
但是恕我直言,你不应该使用内置type
名称来创建一个特定的功能:
def my_type(obj):
return obj.my_type_string if hasattr(obj, 'my_type_string') else str(type(obj))
因为现在它可以始终返回一个字符串