class property(object):
def __init__(self,x):
assert isinstance(x,int),"x=%s must be integer" % x;
self.__x=~x;
def get_x(self):
return ~self.__x;
# def set_x(self,x):
# self.__x=~x;
x=property(get_x);
inst=property(10);
print inst.x
inst.x=16
print inst.x
这个例子在第一次输出10后,第二次将不会输出16,理由是它没有set方法。稍微做下改造:
class property(object):
def __init__(self,x):
assert isinstance(x,int),"x=%s must be integer" % x;
self.__x=~x;
def get_x(self):
return ~self.__x;
def set_x(self,x):
self.__x=~x;
x=property(get_x,set_x);
inst=property(10);
print inst.x
inst.x=16
print inst.x
这次可以正确的输出10和16了。你甚至还可以加入一个文档描述:
x=property(get_x,set_x,doc='a simple property');
注意这里要用:
print property.x.__doc__
可以输出a simple property
但如果改为调用print inst.x.__doc__
则输出int类的描述文档。
像下面这样:
int(x[, base]) -> integer
Convert a string or number to an integer, if possible. A floating point
argument will be truncated towards zero (this does not include a string
representation of a floating point number!) When converting a string, use
the optional base. It is an error to supply a base when converting a
non-string. If the argument is outside the integer range a long object
will be returned instead.
理由是property()函数里的doc是与类绑定的