<分区>
假设你有一个 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
>>>