社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

python属性和方法重写问题:为什么subclass属性仍然调用基类的方法

Anthony Kong • 5 年前 • 837 次点击  

下面是一个例子

class A(object):
        def f1(self):
                return []
        test1 = property(f1)


class B(A):
        def f1(self):
                return [1, 2]

if __name__ == "__main__":
        b = B()
        print b.test1

我希望输出为[1,2],但它打印的是[]。

这与我的期望相反。

我在密码上犯了什么错误吗?如果不是,我想它是这样工作的,因为当创建属性test1时,它被绑定到基类a的f1函数。实现我想要的是什么样的可选实现?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/31053
 
837 次点击  
文章 [ 3 ]  |  最新文章 5 年前
David Z
Reply   •   1 楼
David Z    13 年前

我可以想到两种选择:要么重复呼叫 property 在子类中,

class B(A):
    def f1(self):
        return [1,2]
    test1 = property(f1)

或将属性基于另一个调用 f1 :

class A(object):
    def f1(self):
        return []
    def _f1(self):
        return self.f1()
    test1 = property(_f1)
Alex Martelli
Reply   •   2 楼
Alex Martelli    13 年前

我想是这样的,因为 创建属性test1时, 绑定到的F1函数 基类A

完全正确。

有什么可能的选择 实现我想要的?

另一个间接级别:

class A(object):
    def f1(self): return []
    def _f1(self): return self.f1()
    test1 = property(_f1)

class B(A):
    def f1(self): return [1, 2]
John La Rooy
Reply   •   3 楼
John La Rooy    13 年前

您可以推迟查找 f1 如果不希望污染类命名空间,则使用lambda函数

class A(object):

        def f1(self):
                return []

        test1 = property(lambda x:x.f1())