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

Rig*_*reM 2 python string casting class repr

有没有办法改变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.
Run Code Online (Sandbox Code Playgroud)

Nil*_*ner 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.'
Run Code Online (Sandbox Code Playgroud)

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

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

>>> o = factory('detector')
>>> type(o)
__main__.Detector
Run Code Online (Sandbox Code Playgroud)