是否可以为Python中的类设置默认方法?

Man*_*nix 4 python methods class

假设你有一个 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"
Run Code Online (Sandbox Code Playgroud)

等等。

现在我以交互模式创建该类的实例,并引用它:

>>> c=C(3,4)
>>> c
<__main__.C object at 0x6ffffe67a50>
>>> print(c)
<__main__.C object at 0x6ffffe67a50>
>>>
Run Code Online (Sandbox Code Playgroud)

如果您单独引用该对象,是否可以有一个被调用的默认方法,如下所示?

>>> c
'Nothing to see here, move along'
>>> print(c)
Nothing to see here, move along
>>>
Run Code Online (Sandbox Code Playgroud)

blh*_*ing 6

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

class C:
    def __repr__(self):
        return 'Nothing to see here, move along'
Run Code Online (Sandbox Code Playgroud)

以便:

>>> c=C()
>>> c
Nothing to see here, move along
>>> print(c)
Nothing to see here, move along
>>>
Run Code Online (Sandbox Code Playgroud)