与JavaScript等价的Python`对象定义属性()`

2024-06-01 11:14:23 发布

您现在位置:Python中文网/ 问答频道 /正文

当我从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(){}});的等效操作

注意:我不是在问如何做特定的示例函数,我试图在原始数据类型(str、int、float、list、dict、set等)上定义一个带有getset的属性。


Tags: 元素get键入属性objectfoofunctionjavascript
3条回答

请参阅^{}函数的文档。它有一些例子。以下是Python 2.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

在Python21中,向新样式的类(从object派生的类)添加新属性(也称为成员对象,包括方法)与简单地定义它们一样简单:

class Foo(object):
    def __init__(self):
        self._value = "Bar"

def get_value(self):
    return self._value

def set_value(self, val):
    self._value = val

def del_value(self):
    del self._value

Foo.value = property(get_value, set_value, del_value)
f = Foo()

print f.value
f.value = "Foo"
print f.value

我使用了Dan D.在his answer中提到的^{}内建,但这实际上是在类创建之后分配属性,就像问题所问的那样。在

Online demo

1:在Python3中,它更简单,因为所有类都是新样式的类

如果我没听错,你想编辑现有的类(add方法)检查这个线程Python: changing methods and attributes at runtime

相关问题 更多 >