简体   繁体   English

与JavaScript的`Object.defineProperty()`等效的Python

[英]Python equivalent of JavaScript's `Object.defineProperty()`

As I transition from JavaScript to Python, I noticed I haven't figured out a way to add properties to the data type classes. 从JavaScript过渡到Python时,我注意到我还没有想出将属性添加到数据类型类的方法。 For example, in JavaScript, if I wanted to be able to type arr.last and have it return the last element in the array arr , or type arr.last = 'foo' and to set the last element to 'foo' , I would use: 例如,在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"]

However, in Python, I'm not sure how to do the equivalent of Object.defineProperty(X.prototype,'propname',{get:function(){},set:function(){}}); 但是,在Python中,我不确定如何执行Object.defineProperty(X.prototype,'propname',{get:function(){},set:function(){}});的等效方法Object.defineProperty(X.prototype,'propname',{get:function(){},set:function(){}});

Note: I am not asking for how to do the specific example function, I am trying to be able to define a property with a get and set onto the primitive data types (str, int, float, list, dict, set, etc.) 注意:我不是在问如何执行特定的示例函数,而是想通过getset原始数据类型(str,int,float,list,dict,set等)的属性。 )

In Python 2 1 , adding new attributes (aka member objects, including methods) to a new-style class (one that derives from object ) is as easy as simply defining them: 在Python 2 1中 ,将新属性(又名成员对象,包括方法)添加到新型类(从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

I use the property builtin that Dan D. mentioned in his answer , but this actually assigns the attribute after the class is created, like the question asks. 我使用Dan D.在他的答案中提到的内建property ,但这实际上是在类创建分配属性,就像问题所问的那样。

Online demo 在线演示

1: in Python 3, it's even simpler, since all classes are new-style classes 1:在Python 3中,它更简单,因为所有类都是新型类

See the documentation of the property function. 请参阅property函数的文档。 It has examples. 它有例子。 The following is the result of print property.__doc__ under Python 2.7.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

如果我理解正确,那么您想编辑现有的类(添加方法)检出此线程Python:在运行时更改方法和属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM