从实例列表访问对象

时间:2020-10-10 13:38:26

标签: python class

提供以下课程

class sq():
    def __init__(self,func,x):
        self.func = func
        self.x = x 
    def square(self):
        return self.func(self.x)**2
    
y = lambda x,p: x + p
p_ls =  range(1,11)
x = 0

objects = [sq(lambda x: y(x,pi),x) for pi in p_ls]
squares = [sq(lambda x: y(x,pi),x).square() for pi in p_ls]
#[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
squares1 = [obj.square() for obj in objects]
#[100, 100, 100, 100, 100, 100, 100, 100, 100, 100]

我不明白为什么squares不等于squares1objects列表中的所有对象似乎都在使用p = p_ls[-1]。每次调用该类时,是否可以“存储” func

0 个答案:

没有答案
相关问题