__在Python中获取函数的fu属性

2024-04-19 11:47:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个函数:

>>> def sum(a,b):
...     return a+b
... 
>>> sum.__get__
<method-wrapper '__get__' of function object at 0x18a85f0>
>>> sum.__get__("ghj")
<bound method ?.sum of 'ghj'>

    >>> dir(sum)
    ['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__format__', '***__get__***', '__getattribute__', '__globals__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']
    >>>

我想知道函数的实际用法。如果有人能用函数解释每个属性的实际用法,我将不胜感激。在


Tags: of函数namereducegetdoccodemethod
1条回答
网友
1楼 · 发布于 2024-04-19 11:47:39

记住,在Python中,一切都是对象(甚至是类和函数!) 作为对象,所有函数都有一个__get__方法。在

__get__对于实现descriptors特别有用:

class Celsius:
    def __get__(self, instance, owner): return 9 * (instance.fahrenheit + 32) / 5
    def __set__(self, instance, value): instance.fahrenheit = 32 + 5 * value / 9

class Temperature:
    def __init__(self, initial_f): self.fahrenheit = initial_f
    celsius = Celsius()

t = Temperature(212)
print(t.celsius)
t.celsius = 0
print(t.fahrenheit)

输出:

^{pr2}$

相关问题 更多 >