views:

116

answers:

3

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?

+2  A: 

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]
Alex Martelli
+1  A: 

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)
David Zaslavsky
+3  A: 

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())
gnibbler