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

标签 python string class casting 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.

最佳答案

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

相关文章:

python - 埃拉托色尼筛 - 寻找素数 Python

python - 无法使用 QTableView 在 PyQT 应用程序中显示来自 MySQL 的信息

regex - 使用正则表达式从字符串中提取匹配模式并使用 perl 将其分配给变量

c++ - String::push_back() 不推回

r - 字符串:提取想要的字符而不是删除不需要的字符

C++ 组合,一个对象如何知道它所在的类?

python - 如何使用变量类型正确地对函数进行类型注释?

python 脚本无法调用 azure 上的 chrome 驱动程序

java - 设计具有枚举依赖性的类的最佳方法

javascript类为什么第二个参数getter在下面不起作用