Issue
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)
The above code will have infinite recursion.
The desired result is to print [4, 5]
when I call b.nums
. How may I have the desired result? Thank you.
Solution
You are generating a recursion because the duplicate nums
. You have two ways to solve it:
- Rename the
nums
inside thebar
class with another name - Don't use
super()
but specify the class namefoo()
Option 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)
Having the duplicate property name nums
generate the recursion, because you call:
print(b.nums)
--> return super().gt(3)
--> return [num for num in self.nums if num > x]
--> return super().gt(3)
--> ....
In your for loop you call self.nums
that is the bar().nums
that calls again the for that calls the nums again and again
Option 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)
This will generate a new instance of the class foo
.
Answered By - Carlo Zanocco
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.