一种覆盖 'type()' 报告内容的方法

A way to override what 'type()' reports

有没有办法改变 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.

你不应该那样做。相反,您应该实现两个单独的 classes,它们都继承自 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.'

如果你想根据你提供的字符串切换你的 class,你可以实现一个 returns 所需对象的工厂:

def factory(t):
    if 'detector' in t:
        return Detector()
    else:
        return Broadcaster()

>>> o = factory('detector')
>>> type(o)
__main__.Detector

可以,但是很危险。 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))

因为现在它可以始终如一地return一个字符串