python - 是否可以在 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
>>>
解决方案
您正在寻找的是__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
>>>
推荐阅读
- html - 每个 Dropbox 更改事件的 HTML 页面更新
- javascript - 在 JavaScript 中访问嵌套的对象数组
- azure - Azure AD B2C 与适用于 Kubernetes 的 EasyAuth
- c++ - 为什么字符串的哈希值相同?
- python - 在 discord.py 中导入除 youtube_dl 以外的任何内容(最好是 soundcloud)
- javascript - 如何在反应中解决“TypeError:无法读取未定义的属性'类别'”?
- xaml - 如果稍微倾斜 ios 设备,sfcombobox 会在 xamarin 表单中向上滚动
- ios - 如何验证 X.509 证书是否由另一个证书签名?
- c++ - 我应该为 vDSP 中的真正 FFT 函数提供什么?
- asp.net - 使用 ajax asp.net 调用 Web 服务