当我从JavaScript过渡到Python时,我注意到我还没有找到向数据类型类添加属性的方法。例如,在JavaScript中,如果我希望能够键入arr.last
并让它返回数组arr
中的最后一个元素,或者输入arr.last = 'foo'
并将最后一个元素设置为'foo'
,我将使用:
Object.defineProperty(Array.prototype,'last',{
get:function(){
return this[this.length-1];
},
set:function(val){
this[this.length-1] = val;
}
});
var list = ['a','b','c'];
console.log(list.last); // "c"
list.last = 'd';
console.log(list); // ["a","b","d"]
但是,在Python中,我不知道如何执行相当于Object.defineProperty(X.prototype,'propname',{get:function(){},set:function(){}});
的操作
get
备注:我是而不是,询问如何执行特定的示例函数,我试图在原始数据类型(str、int、float、list、dict、set等)上定义一个带有和的属性。
发布于 2015-09-03 16:54:47
请参阅property
函数的文档。它有例子。以下是Python2.7.3下的print property.__doc__
的结果:
property(fget=None, fset=None, fdel=None, doc=None) -> property attribute
fget is a function to be used for getting an attribute value, and likewise
fset is a function for setting, and fdel a function for del'ing, an
attribute. Typical use is to define a managed attribute x:
class C(object):
def getx(self): return self._x
def setx(self, value): self._x = value
def delx(self): del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")
Decorators make defining new properties or modifying existing ones easy:
class C(object):
@property
def x(self): return self._x
@x.setter
def x(self, value): self._x = value
@x.deleter
def x(self): del self._x
发布于 2015-09-03 16:50:26
如果我正确地理解了您,您希望编辑现有的类(添加方法),检查这个线程Python:在运行时更改方法和属性
https://stackoverflow.com/questions/32387549
复制相似问题