使用其相关方法时如何覆盖固有的属性?

How to override the an inherent property when using its related method?

class foo:

   @property
   def nums(self):
       return [1, 2, 3, 4, 5]

   def gt(self, x):
       return [num for num in self.nums if num > x] 

class bar(foo):

    @property
    def nums(self):
        return super().gt(3)

f = foo()
b = bar()

print(f.nums)
print(b.nums)

以上代码会无限递归。

期望的结果是当我调用b.nums时打印[4, 5]。我怎样才能得到想要的结果?谢谢。

您正在生成递归,因为重复 nums。您有两种解决方法:

  • bar 中的 nums class 重命名为另一个名称
  • 不要使用 super() 但指定 class 名称 foo()

选项 1

class foo:
    @property
    def nums(self):
       return [1, 2, 3, 4, 5]

    def gt(self, x):
       return [num for num in self.nums if num > x] 

class bar(foo):
    @property
    def diffrent_nums(self):
        return super().gt(3)

f = foo()
b = bar()

print(f.nums)
print(b.diffrent_nums)

具有重复的 属性 名称 nums 生成递归,因为您调用:

print(b.nums) --> return super().gt(3) --> return [num for num in self.nums if num > x] --> return super().gt(3) --> ....

在您的 for 循环中,您调用 self.numsbar().nums 再次调用 for 一次又一次地调用 nums

选项 2

class foo:
    @property
    def nums(self):
       return [1, 2, 3, 4, 5]

    def gt(self, x):
       return [num for num in self.nums if num > x] 

class bar(foo):
    @property
    def nums(self):
        return foo().gt(3)

f = foo()
b = bar()

print(f.nums)
print(b.nums)

这将生成 class foo 的新实例。

您的实施默认为 non-logical。 class bar 中的函数 nums 覆盖 class foo 中的函数 nums - 因此当您调用 self.nums 时 list-comprehension 的 gt 函数 - 实际调用的 numsbar.

中的覆盖函数

不确定你的约束是什么,但只要不覆盖就可以了:

class foo:

   @property
   def nums(self):
       return [1, 2, 3, 4, 5]

   def gt(self, x):
       return [num for num in self.nums if num > x] 

class bar(foo):

    @property
    def nums2(self):
        return super().gt(3)

f = foo()
b = bar()

print(f.nums)
print(b.nums2)

另一种选择是使 nums 成为成员,并使 return 来自 nums,如下所示:

class foo:
    nums_member = [1, 2, 3, 4, 5]
    @property
    def nums(self):
       return self.nums_member

    def gt(self, x):
       return [num for num in self.nums_member if num > x] 

class bar(foo):

    @property
    def nums(self):
        return super().gt(3)

f = foo()
b = bar()

print(f.nums)
print(b.nums)