Python 类复杂数据描述符或类变量的real和imag?
您应该知道python中的类Python 类复杂数据描述符或类变量的real和imag?,python,class,complex-numbers,Python,Class,Complex Numbers,您应该知道python中的类complex。它包括: >>> dir(complex) Output : ['__abs__', '__add__', '__bool__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__get
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']
这里,共轭
是类复数
的一种方法。但我的疑问是,什么是真实的,什么叫做imag
在help()中:
在help()中,real和imag作为数据描述符给出
类型()中的位置:
因此,我有一个疑问。real和imag是类变量还是数据描述符???
类似地,类范围中的开始
、停止
和步骤
中存在疑问
需要澄清:
它们是数据描述符还是类变量
如果它们是数据描述符,请解释为什么它们被称为数据描述符
任何与我的疑问有关的数据描述符的参考链接都是非常需要的
提前感谢A,当它被存储为类变量时,当它通过实例进行查找时,会在其上运行特殊的方法
描述符协议用于几种特殊行为,例如方法绑定(如何将self
作为第一个参数传递)。通过属性
类型,Python代码可以轻松使用该协议,该类型是一个描述符,您可以将其作为方法的装饰器应用,以便在查找属性时调用它(无需用户显式调用任何内容)
在您的例子中,complex
类型的real
和imag
属性(以及范围
类型的三个属性)是描述符,但它们没有其他属性那么花哨。相反,描述符只是不可变内置类(即用C实现的类,而不是纯Python实现的类)实例的属性访问方式。复杂对象(或范围对象)的实际数据存储在C结构中。描述符允许Python代码访问它。请注意,您不能为这些属性赋值,因为这样会破坏对象的不变性
您可以使用属性实现类似的类型:
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
类型中的描述符类似的描述符。它们也是只读的(尽管类作为一个整体并不是真正不可变的)。real
和imag
是复数的只读属性。您可以使用它们来获得复数的实部和虚部。没有比这更重要的了。
>>> a=1j
>>> type(a.real)
<class 'float'>
>>> type(a.imag)
<class 'float'>
classname.class_variable (or) objectname.class_variable
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