[英]A way to override what 'type()' reports
Is there a way to alter a CLASS OBJECT so that type(object)
reports a custom string? 有没有办法改变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.
You should not do that. 你不应该这样做。 Instead you should implement two separate classes, both of which inherit from
MyClass
: 相反,你应该实现两个独立的类,这两个类都继承自
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.'
And if you want to switch your class depending on a string you provide you could implement a factory that returns the desired object: 如果你想根据你提供的字符串切换你的类,你可以实现一个返回所需对象的工厂:
def factory(t):
if 'detector' in t:
return Detector()
else:
return Broadcaster()
>>> o = factory('detector')
>>> type(o)
__main__.Detector
You can, but it is dangerous. 你可以,但这很危险。
type
is a builtin, and other places could use it. type
是内置的,其他地方可以使用它。 But if you know what you are doing and why you do it, you can redefine type
. 但是如果你知道自己在做什么以及为什么要这样做,你可以重新定义
type
。 but Here be dragons. 但这里有龙。 You've been warned.
你被警告过了。 :
:
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)
But IMHO, you should not use the builtin type
name for that use, but create a specific function: 但恕我直言,你不应该使用内置
type
名称,但创建一个特定的功能:
def my_type(obj):
return obj.my_type_string if hasattr(obj, 'my_type_string') else str(type(obj))
because now it can consistently return a string 因为现在它可以始终返回一个字符串
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.