首页 > 解决方案 > 实例可以返回 __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__,但到目前为止还没有运气。

标签: pythoninstanceinstance-variablesmagic-methods

解决方案


推荐阅读