luofeiyu_cu 发表于 2014-08-21 21:33

描述符的困惑

http://bbs.chinaunix.net/thread-1812710-1-1.html

那个帖子非常好,但是有个地方感觉有歧义,下面的代码摘录如下(改成python34下面可以运行):

class MyDescriptor(object):
   def __init__(self, x):
         self.x = x
   def __get__(self, instance, owner):
         print('get from descriptor')
         return self.x
   def __set__(self, instance, value):
         print('set from descriptor')
         self.x = value
   def __delete__(self, instance):
         print('del from descriptor, the val is', self.x)

这里的x和self.x中的x容易搞混,个人感觉要改过来,如果不改,请看:

exam=MyDescriptor("hallo")
当你将它实例化的时候,hallo是对应__init__(self, x),x=hallo ,hallo作为参数传进去了,

self.x容易理解成self.hallo ,太容易产生这种误解了。改成下面较好。

class MyDescriptor(object):
   def __init__(self, x):
         self.y = x
   def __get__(self, instance, owner):
         print('get from descriptor')
         return self.y
   def __set__(self, instance, value):
         print('set from descriptor')
         self.y = value
   def __delete__(self, instance):
         print('del from descriptor, the val is', self.y)

exam=MyDescriptor("hallo")
exam有个y属性,根本不和x混在一起,我的建议有道理吗?

icymirror 发表于 2014-08-22 10:43

只能说,无语。:-L

sxcong 发表于 2014-08-22 10:50

变量和值是两回事。
你这个"hello",别人不会误解成一个叫hello的变量的。
页: [1]
查看完整版本: 描述符的困惑