你会知道python中的类complex
。它包含:
>>> 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()中,实数和imag作为数据描述符给出。
其中在类型():
>>> a=1j
>>> type(a.real)
<class 'float'>
>>> type(a.imag)
<class 'float'>
此外,当我们访问类中的类变量时,我们正在访问实数和 imag。
classname.class_variable (or) objectname.class_variable
因此,我在这里产生了怀疑。实数和 imag 是一种类变量还是数据描述符??? 同样,start
中的疑问,stop
和类range
中的step
。
需要澄清:
它们是数据描述符还是一种类变量?
如果它们是数据描述符,请解释为什么它们被称为数据描述符???
非常需要任何与我的疑问相关的数据描述符的参考链接
提前致谢
描述符是 Python 中的一种特殊对象,当它存储为类变量时,当它通过实例查找时,它会在其上运行特殊方法。
描述符协议用于几种特殊行为,例如方法绑定(如何将self
作为第一个参数传递)。该协议可通过property
类型轻松用于 Python 代码,这是一个描述符,您可以将其作为装饰器应用于方法,以便在查找属性时调用它(无需用户显式调用任何内容)。
在您的情况下,complex
类型的real
和imag
属性(以及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
类型中的描述符。它们也是只读的(尽管整个类并不是真正不可变的)。