从 Python 中的不同对象访问相同的属性 [英] Access the same attribute from different objects in Python

查看:121
本文介绍了从 Python 中的不同对象访问相同的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为 Cube 的类并且我创建了三个对象:

class Cube():def __init__(self, volume):self.volume = 音量a = Cube(param_a)b = 立方体(param_b)c = 立方体(param_c)

我想知道我是否可以编写一个函数,用户可以为其提供格式,并且该函数可以将格式应用于对象?例如:

<预><代码>>>>打印所有(dummy_cube.volume)a.体积b.体积c.体积

所以基本上这个函数包含一个循环,它将把 dummy_cube 替换为 a、b、c.我知道我可以使用 getattr() 之类的东西,但它有限制.例如,我希望该函数可以打印用户给出的任何格式:

<预><代码>>>>print_all( (dummy_cube.volume)**2 + 1 )(a.volume)**2 + 1(b.volume)**2 + 1(c.volume)**2 + 1

有什么好的办法吗?

正如评论所指出的,是的,该函数可以接受一个列表,我打算它返回数值而不是格式本身.有了我可以做的清单:

cube_list = [a, b, c]对于cube_list 中的立方体:打印((立方体.体积)**2 + 1)

但我仍然不确定如何使用用户给出的任意表达式来做到这一点.

解决方案

用户可以提供一个函数.

def print_all(f):对于cube_list 中的立方体:打印(f(立方体))进口经营者print_all(operator.attrgetter('volume'))print_all(lambda c: c.volume**2 + 1)

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.

解决方案

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)

这篇关于从 Python 中的不同对象访问相同的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆