python属性和继承 [英] python properties and inheritance

查看:149
本文介绍了python属性和继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有属性的基类,我想在子类中覆盖它(get方法)。我的第一个想法是:

I have a base class with a property which (the get method) I want to overwrite in the subclass. My first thought was something like:

class Foo(object):
    def _get_age(self):
        return 11

    age = property(_get_age)


class Bar(Foo):
    def _get_age(self):
        return 44

这不起作用(子类bar.age返回11)。我找到了一个带有lambda表达式的解决方案:

This does not work (subclass bar.age returns 11). I found a solution with an lambda expression which works:

age = property(lambda self: self._get_age())

这是使用属性并在子类中覆盖它们的正确解决方案,还是有其他首选方法这样做?

So is this the right solution for using properties and overwrite them in a subclass, or are there other preferred ways to do this?

推荐答案

我只想重复属性()以及在重写类方法时,您将重复 @classmethod 装饰器。

I simply prefer to repeat the property() as well as you will repeat the @classmethod decorator when overriding a class method.

虽然这看起来非常冗长,但至少对于Python标准,你可能会注意到:

While this seems very verbose, at least for Python standards, you may notice:

1)只有属性,属性可以用作装饰器:

1) for read only properties, property can be used as a decorator:

class Foo(object):
    @property
    def age(self):
        return 11

class Bar(Foo):
    @property
    def age(self):
        return 44

2)在Python 2.6中,属性增长了一对方法 setter 删除,可用于向常规属性应用已经可用于只读属性的快捷方式:

2) in Python 2.6, properties grew a pair of methods setter and deleter which can be used to apply to general properties the shortcut already available for read-only ones:

class C(object):
    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

这篇关于python属性和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆