python文本分類,python 描述器 詳解_描述器使用指南

 2023-09-28 阅读 28 评论 0

摘要:Python 的面向對象功能是在基于函數的環境構建的。通過使用非數據描述器,這兩方面完成了無縫融合。 Functions stored in class dictionaries get turned into methods when invoked. Methods only differ from regular functions in that the object instance is prep

Python 的面向對象功能是在基于函數的環境構建的。通過使用非數據描述器,這兩方面完成了無縫融合。

Functions stored in class dictionaries get turned into methods when invoked.

Methods only differ from regular functions in that the object instance is

prepended to the other arguments. By convention, the instance is called

python文本分類?self but could be called this or any other variable name.

Methods can be created manually with types.MethodType which is

roughly equivalent to:

class MethodType:

"Emulate Py_MethodType in Objects/classobject.c"

python需要編譯嗎?def __init__(self, func, obj):

self.__func__ = func

self.__self__ = obj

def __call__(self, *args, **kwargs):

func = self.__func__

python描述器、obj = self.__self__

return func(obj, *args, **kwargs)

To support automatic creation of methods, functions include the

__get__() method for binding methods during attribute access. This

means that functions are non-data descriptors that return bound methods

python getattr。during dotted lookup from an instance. Here's how it works:

class Function:

...

def __get__(self, obj, objtype=None):

"Simulate func_descr_get() in Objects/funcobject.c"

將數據用python描述、if obj is None:

return self

return MethodType(self, obj)

Running the following class in the interpreter shows how the function

descriptor works in practice:

python五大器。class D:

def f(self, x):

return x

The function has a qualified name attribute to support introspection:

>>>D.f.__qualname__

python -m?'D.f'

Accessing the function through the class dictionary does not invoke

__get__(). Instead, it just returns the underlying function object:

>>>D.__dict__['f']

python語言?Dotted access from a class calls __get__() which just returns the

underlying function unchanged:

>>>D.f

The interesting behavior occurs during dotted access from an instance. The

python元編程、dotted lookup calls __get__() which returns a bound method object:

>>>d = D()

>>>d.f

>

Internally, the bound method stores the underlying function and the bound

python 描述符?instance:

>>>d.f.__func__

>>>d.f.__self__

<__main__.D object at 0x1012e1f98>

python語言簡介,If you have ever wondered where self comes from in regular methods or where

cls comes from in class methods, this is it!

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/5/102858.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息