从描述符文档中:
描述符可以通过其方法名称直接调用。例如,
d.__get__(obj)
。
下一个类的例子是什么?
class Descriptor:
def __init__(self, color="red"):
self.color = color
例如,什么是d
什么,什么是什么obj
?"d.__get__(obj)"
上述类/实例将如何调用?
为了使您的示例成为描述符,它需要一个__get __()方法:
class Descriptor:
def __init__(self, color="red"):
self.color = color
def __get__(self, obj, objtype=None):
return obj.size + ' ' + self.color
在另一个类中使用该描述符:
class A:
pair = Descriptor('green')
def __init__(self, size):
self.size = size
像这样调用描述符:
>>> a = A('big')
>>> a.pair
'big green'
希望这个工作示例可以帮助您:-)
1)如果定义了__get __(),__set __()或_ _delete __()中的任何一个,则类是一个描述符。
2)通过创建描述符的实例并将其作为类变量存储在另一个类中来使其工作。
3)使用点运算符调用具有常规属性查找的描述符。
真的就是全部了:-)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句