python - 类复杂数据描述符或类变量的实数和图像?
问题描述
你会知道complex
python 中的类。它包含 :
>>> dir(complex)
Output :
['__abs__', '__add__', '__bool__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__int__', '__le__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__pos__', '__pow__', '__radd__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__rpow__', '__rsub__', '__rtruediv__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', 'conjugate', 'imag', 'real']
这conjugate
是一个类的方法complex
。但我的疑问是什么是真实的和想象的?
在帮助()中:
>>>help(complex)
Output:
class complex(object)
| complex(real=0, imag=0)
...
...
...
----------------------------------------------------------------------
| Data descriptors defined here:
|
| imag
| the imaginary part of a complex number
|
| real
| the real part of a complex number
在 help() 中,real 和 imag 作为数据描述符给出。
在类型()中的位置:
>>> a=1j
>>> type(a.real)
<class 'float'>
>>> type(a.imag)
<class 'float'>
当我们访问类中的类变量时,我们也在访问 real 和 imag。
classname.class_variable (or) objectname.class_variable
因此,我在这里产生了疑问。real 和 imag 是一种类变量还是数据描述符???start
同样,在stop
和step
在课堂上的疑问range
。
需要澄清:
它们是数据描述符还是一种类变量?
如果它们是数据描述符,请解释一下为什么它们被称为数据描述符???
非常需要任何与我的疑问相关的数据描述符的参考链接
提前致谢
解决方案
描述符是 Python 中的一种特殊对象,当它作为类变量存储时,当通过实例查找它时,会在其上运行特殊方法。
描述符协议用于几种特殊行为,例如方法绑定(如何self
作为第一个参数传递)。通过property
type 可以轻松地为 Python 代码提供协议,这是一个描述符,您可以将其作为装饰器应用于方法,以便在查找属性时调用它(无需用户显式调用任何内容)。
在您的情况下,类型的real
andimag
属性complex
(以及类型的三个属性range
)是描述符,但它们没有其他的那么花哨。相反,描述符只是属性访问对不可变内置类的实例(即,在 C 中实现的,而不是在纯 Python 中实现的)的工作方式。complex
(或)对象的实际数据range
存储在 C 结构中。描述符允许它被 Python 代码访问。请注意,您不能分配给这些属性,因为这会破坏对象的不变性。
您可以使用以下方法实现类似的类型property
:
class MyComplex():
def __init__(self, real=0, imag=0):
self._real = real
self._imag = imag
@property
def real(self):
return self._real
@property
def imag(self):
return self._imag
这里real
和imag
是property
对象,它们是类似于内置complex
类型中的描述符。它们也是只读的(尽管整个类并不是真正不可变的)。
推荐阅读
- sql - 如何将 xml 标签中的值分隔到 SQL 中的新行中
- c++ - what does operator"" overloading mean in C++?
- javascript - javascript中的刽子手,当字母错误时返回总是正确的
- react-jsonschema-forms - Custom ui:widget will not alter the formData
- typo3 - RealURL 无法找到域“xyz.com”的根页面 ID
- java - java中十进制数字的总和
- java - SAML 失败响应中的颁发者
- python-3.x - 如何使用 Python 从 GMail 中注销
- database - 如何处理压缩十进制字段上的 AS400 DB2 数据溢出?
- templates - 将模板划分为文件错误