简体   繁体   中英

Python property and method override issue: why subclass property still calls the base class's method

Here is an example

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

I expect the output to be [1, 2], but it prints [] instead.

It is contrary to my expectation.

Did I make any mistake in the code? If not, I suppose it works this way because when the property test1 is created, it is bound to the f1 function of the base class A. What is a possible alternative implementation to achieve what I want?

You can defer the lookup of f1 with a lambda function if you don't wish to pollute the class namespace

class A(object):

        def f1(self):
                return []

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

I suppose it works this way because when the property test1 is created, it is bound to the f1 function of the base class A.

Exactly correct.

What is a possible alternative implementation to achieve what I want?

One more level of indirection:

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]

A couple of alternatives I can think of: either repeat the call to property in the subclass,

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

or base the property on another method which calls f1 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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