首页 > 解决方案 > 是否可以在 python 中为类设置默认方法?

问题描述

假设你在 python 中有一个类。我们会调用它C。并假设您在脚本的某处或以交互模式创建它的实例:c=C()

是否可以在类中有一个“默认”方法,这样当您引用实例时,会调用该默认方法?

class C(object):
    def __init__(self,x,y):
        self.x=x
        self.y=y
    def method0(self):
        return 0
    def method1(self):
        return 1
    def ...
        ...
    def default(self):
        return "Nothing to see here, move along"

等等。

现在我在交互模式下创建一个类的实例,并引用它:

>>> c=C(3,4)
>>> c
<__main__.C object at 0x6ffffe67a50>
>>> print(c)
<__main__.C object at 0x6ffffe67a50>
>>>

如果您自己引用对象,是否可以调用默认方法,如下所示?

>>> c
'Nothing to see here, move along'
>>> print(c)
Nothing to see here, move along
>>>

标签: pythonclassmethods

解决方案


您正在寻找的是__repr__方法,它返回类实例的字符串表示形式。您可以像这样覆盖该方法:

class C:
    def __repr__(self):
        return 'Nothing to see here, move along'

以便:

>>> c=C()
>>> c
Nothing to see here, move along
>>> print(c)
Nothing to see here, move along
>>>

推荐阅读