python - 实例可以返回 __repr__ 字符串表示以外的值吗?
问题描述
这是我正在研究的现象的一个示例:
class Person:
def __init__(self, name, other):
self.name = name
self.other = other
class Name():
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
def __repr__(self):
return self.firstname + " " + self.lastname
class Other():
def __init__(self, age, stats):
self.age = age
self.stats = stats
self.other = (self.age, self.stats)
def __repr__(self):
return (self.age, self.stats)
person_one = Person(Name("John", "Doe"), Other(29, [1, 2, 3]))
print(person_one.name.firstname)
print(person_one.name.lastname)
print(person_one.name.name)
print(person_one.name)
print(person_one.other.age)
print(person_one.other.stats)
print(person_one.other.other)
print(person_one.other)
除了最后一行代码,一切都会正常工作,这会产生 TypeError。那是因为__repr__
/__str__
魔法方法只会返回一个字符串。
所以我的问题是,有没有办法获得可以返回非字符串的类似功能?我的意思是,除了在 person_one.name.name 和 person_one.other.other 用法中使用重复的实例变量之外?
我看到一些东西表明这可以通过___new___
魔术方法实现,但我不确定它是如何工作的。
我知道这没什么大不了的,如果这根本不可能,请告诉我,但这似乎是一个非常方便且合乎逻辑的结构,可以使用。
编辑:
看来我可以通过修改__call__
.
例如,如果我添加到class Other()
:
def __call__(self):
return (self.age, self.stats)
现在person_one.other()
将返回元组。但是,如果我能让person_one.other
自己返回一个元组(不破坏拥有person_one.other.age
等的能力,返回他们想要的东西),那仍然会很好。我正在看__getattribute__
,但到目前为止还没有运气。
解决方案
推荐阅读
- python - 我需要基于 json 格式的电子邮件类型(个人和专业)的电子邮件列的多值字段(数组)
- excel - 带功能的roo导入单元格
- mysql - 子查询在更新语句中使用外键返回多行
- google-cloud-platform - 我的 Cloud Build 服务帐户需要哪些角色来部署 http 触发的未经身份验证的 Cloud Function?
- java - 由于 Hibernate 从 information_schema.sequences 中选择不存在的列,无法加载 ApplicationContext
- .net - 本地机器 appsettings.json 文件未在生产环境中覆盖
- asp.net-mvc - 使用 Microsoft.AspNetCore.Identity 设计的应用程序的 SSO 实施
- python - 如何诊断 django 渲染速度问题?
- javascript - CSS transitions won't happen simultaneously after classList.toggle
- javascript - 如何将元素宽度作为道具传递?