有没有办法改变 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.
最佳答案
你不应该那样做。相反,您应该实现两个独立的类,它们都继承自 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
关于python - 一种覆盖 'type()' 报告内容的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42907790/