0

Suppose I have a class called Cube and I create three objects:

class Cube():
    def __init__(self, volume):
        self.volume = volume

a = Cube(param_a)
b = Cube(param_b)
c = Cube(param_c)

I was wondering if I can write a function, to which the user can give a format, and the function can apply the format to the objects? For example:

>>> print_all(dummy_cube.volume)
a.volume
b.volume
c.volume

So basically the function contains a loop which will replace dummy_cube to a, b, c. I know I can use something like getattr(), but it has limits. For example, I hope that the function can print whatever format the user gives:

>>> print_all( (dummy_cube.volume)**2 + 1 )
(a.volume)**2 + 1
(b.volume)**2 + 1
(c.volume)**2 + 1

Is there any good way to do this?

Edit: As the comments pointed out, yes the function can take a list, and I intend it to return the numerical values instead of the format itself. With a list I can do like:

cube_list = [a, b, c]
for cube in cube_list:
    print( (cube.volume)**2 + 1 )

But I am still not sure how I can do it with arbitrary expressions given by the user.

SpencerYD
  • 33
  • 5
  • 1
    It sounds like you need to make a list instead of using 3 separate variables. – user2357112 May 26 '20 at 21:18
  • If your function accepts a list of objects as well as a format, this can be done. – Ahmet May 26 '20 at 21:19
  • Are you looking to print out "(a.volume)**2 + 1 " ,or the result of it, i.e. (10)**2+1=101. Do you want to print out 101, or print this specific style, " (a.volume)**2 + 1"? – Akib Rhast May 26 '20 at 21:20
  • Create a list of `Cube` instances. You can then iterate through the list via a `for` loop and access the attributes of each one. – martineau May 26 '20 at 21:23
  • I put more details in the question. Yeah the function can accept a list, but I am still confused what to do after this. And I want to print the value instead of the specific style. – SpencerYD May 26 '20 at 21:31

1 Answers1

3

The user can supply a function.

def print_all(f):
    for cube in cube_list:
        print(f(cube))

import operator

print_all(operator.attrgetter('volume'))
print_all(lambda c: c.volume**2 + 1)
Barmar
  • 741,623
  • 53
  • 500
  • 612