简体   繁体   English

Python属性魔术

[英]Python property magic

When is the inner() function actually getting called in this simple code snippet? 在此简单的代码片段中,何时真正调用inner()函数? I have read about python properties, but I am unsure what magic is it doing here. 我已经阅读了有关python属性的信息,但是我不确定它在做什么。

>>> class Magic:
...     @property
...     def __repr__(self):
...         def inner():
...             return "It works!"
...         return inner
...
>>> repr(Magic())
'It works!'

When I remove "@property" , I get an expected error: 删除"@property" ,出现预期的错误:

TypeError: __repr__ returned non-string (type function)

__repr__ is supposed to give a human-readable representation of the object... __repr__应该给出人类可读的对象表示形式...

Return a string containing a printable representation of an object. 返回包含对象的可打印表示形式的字符串。

For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object . 对于许多类型,此函数会尝试返回一个字符串,该字符串在传递给eval()时将产生具有相同值的对象,否则表示形式是一个用尖括号括起来的字符串,其中包含该对象的类型名称附加信息通常包括对象的名称和地址 A class can control what this function returns for its instances by defining a __repr__() method. 一个类可以通过定义__repr __()方法来控制此函数为其实例返回的内容。

You are returning a function. 您正在返回一个函数。 Try: 尝试:

>>> class Magic:
...     def __repr__(self):
...         def inner():
...             return "It works!"
...         return inner()
...
>>> repr(Magic())
'It works!'

It's also worth reading up on the @property decorator, and decorators in general... See this answer . 还值得阅读@property装饰器,以及一般的装饰器...请参阅此答案


To answer youy " When is the inner() function actually getting called? ", see below. 要回答您“ 何时真正调用inner()函数? ”,请参见下文。 It's getting called when repr() calls Magic.__repr__() on your behalf. repr() Magic.__repr__()您调用Magic.__repr__()时,它将被调用。

#!/usr/bin/env python3

def my_decorator(info):
    def my_dec_inner(self):
        return "Testing"
    return my_dec_inner

class Magic:
    @my_decorator
    def __repr__(self):
        def inner():
            return "It works!"
        return inner

m = Magic()

# these are nearly synonymous
print(m.__repr__())
print(repr(m))

# this is actually a 'bound function' - my_decorator
print(m.__repr__)
Testing
Testing
<bound method Magic.my_dec_inner of Testing>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM