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

查看:29
本文介绍了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?

推荐答案

我只是喜欢重复 property() 以及重复 @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) 对于只读属性,property 可以用作装饰器:

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 中,属性增长了一对方法 setterdeleter 可用于将已可用于只读属性的快捷方式应用于通用属性:

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天全站免登陆