一个更好的python属性装饰器

jtm*_*jtm 3 python debugging properties decorator

我继承了一些python代码,其中包含一个相当神秘的装饰器.此装饰器在整个项目的类中设置属性.问题是,我已将此调试问题跟踪到此装饰器.似乎它"fubars"我试过的所有调试器,并试图加速psyco休息的代码.(似乎psyco和这个装饰师不好玩).我认为最好改变它.

def Property(function):
    """Allow readable properties"""
    keys = 'fget', 'fset', 'fdel'
    func_locals = {'doc':function.__doc__}
    def probeFunc(frame, event, arg):
        if event == 'return':
            locals = frame.f_locals
            func_locals.update(dict((k,locals.get(k)) for k in keys))
            sys.settrace(None)
        return probeFunc
    sys.settrace(probeFunc)
    function()
    return property(**func_locals)
Run Code Online (Sandbox Code Playgroud)

像这样使用:

class A(object):
    @Property
    def prop():
        def fget(self):
            return self.__prop
        def fset(self, value):
            self.__prop = value
    ... ect
Run Code Online (Sandbox Code Playgroud)

我得到的错误说问题是因为sys.settrace.(也许这是滥用settrace?)

我的问题:没有 sys.settrace,是否可以实现相同的装饰器.如果不是,我正在进行一些重写.

Tho*_*ers 8

同一件事情?没有.如果没有像sys.settrace这样的魔法,你就无法做那个装饰器.(从技术上讲,它不一定是sys.settrace,但使用其他东西 - 比如字节码重写 - 不会有任何改进.)你可以通过这样做来简化它,例如:

def Property(f):  
    fget, fset, fdel = f()
    fdoc = f.__doc__
    return property(fget, fset, fdel, fdoc)

class Foo(object):
    @Property
    def myprop():
        "Property docstring"
        def fget(self):  
            return 'fget' 
        def fset(self, x):
            pass
        def fdel(self):
            pass
        return fget, fset, fdel
Run Code Online (Sandbox Code Playgroud)

在Python 2.6及更高版本中,您可以使用略有不同的装饰器:

def Property(cls):
    fget = cls.__dict__.get('fget')
    fset = cls.__dict__.get('fset')
    fdel = cls.__dict__.get('fdel')
    fdoc = cls.__doc__
    return property(fget, fset, fdel, fdoc)
Run Code Online (Sandbox Code Playgroud)

你会像这样使用它:

class Foo(object):
    @Property
    class myprop(object):
        "Property docstring"
        def fget(self):
            return 'fget'
        def fset(self, x):
            pass
        def fdel(self):
            pass
Run Code Online (Sandbox Code Playgroud)

但是,在Python 2.6及更高版本中执行此操作的更惯用的方法是这样的:

class Foo(object):
    @property
    def myprop(self):
        "Property docstring"
        return 'fget'
    @myprop.setter
    def myprop(self, x):
            pass
    @myprop.deleter
    def myprop(self):
            pass
Run Code Online (Sandbox Code Playgroud)

  • 我完全用惯用的python方式做事,但最后一个例子似乎不像我继承的"巫毒"装饰器那么可读.也许我只需要习惯它.(惯用的方式,就是这样) (2认同)