简体   繁体   中英

List Comprehension Function Pointer Python

I have a method (dosomething) that defines an attribute (self.b). Dummy code below:

class foo:
    def __init__(self):
        self.a = 1
    def dosomething(self, i):
        self.b = 2 * self.a + i
        return self.b ** 2 
testobj = foo()

Attribute a can change - so dosomething is called to determine b given the current value of a.

I want to write a list comprehension like the one below. Except, I need to call dosomething for b to change. The dummy code below would just repeat the current value of self.b 20 times.

[testobj.b for i in range(20)] # pass i to dosomething then store self.b

The quick way is to just return self.b but, the return statement is preoccupied for another value that's much more complicated. If I could return self.b, then the following statement would work:

[testobj.dosomething(i) for i in range(20)]

Attribute b is just an intermediate value that I want to access. Is there a one liner list comprehension for this situation? I was considering defining a function within the method that returns self.b but, I'm not sure how I would be able to access it properly. So something like foo().dosomething(1).getb() wouldn't work because dosomething(1) evaluates to a number.

class foo:
    def __init__(self):
        self.a = 1
    def dosomething(self, i):
        self.b = 2 * self.a + i
        def getb():
            return self.b
        return self.b ** 2 

I guess I should also add that I don't want to be returning a data structure of different values. It would effect much of my code elsewhere.

Not a good use case for list comprehensions.

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