Python如何将属性添加到函数中的现有对象

标签 python flask

我正在尝试创建一个动态函数来动态添加属性,以便轻松地在 jinja 模板中访问值。

此代码有效,但它是静态的。

# Used to display a cart summary of items that have been pledged.
products_in_cart = Cart.query.filter(Cart.campaign_id == campaign_id).all()
# total_cart_quantity(products_in_cart, "quantity", "quantity_total")
for item in products_in_cart:
    item.quantity_total = 0 #Adding the attribute quantity_total

    for item_loop2 in products_in_cart:
        if item.user_id == item_loop2.user_id:
            item.quantity_total = item.quantity_total + item_loop2.quantity

# Remove duplicate objects based on user_id attribute.
new_set = set()
new_list = []
for obj in products_in_cart:
    if obj.user_id not in new_set:
        new_list.append(obj)
        new_set.add(obj.user_id)

products_in_cart = new_list

我想根据传入函数的参数使添加的属性名称动态化,以便我可以在其他地方使用。点符号不起作用,因为我需要一个变量来命名属性。 obj[variable_attrbute] 错误。 setattr() 什么都不做。

def total_cart_quantity(cart_objects, sum_attribute, new_attribute):
'''
    From cart get the total of a particular quantity and add it to a new attribute.
    cart_objects = the queried cart_objects.
    sum_attribute = the attribute to be summed.
    new_attribute = the string of the new attribute name
'''
for item in cart_objects:
    # Two different attempts to add an attribute. 
    # setattr will just not add the attribute
    setattr(item, sum_attribute, new_attribute) # this will do nothing
    # item[new_attribute] = 0 # this will error

    for item_loop2 in cart_objects:
        if item.user_id == item_loop2.user_id:
            item[new_attribute] = item[new_attribute] + item_loop2[sum_attribute]

# Remove duplicate objects based on user_id attribute.
new_set = set()
new_list = []
for obj in cart_objects:
    if obj.user_id not in new_set:
        new_list.append(obj)
        new_set.add(obj.user_id)

products_in_cart = new_list

return products_in_cart

如何动态添加属性名称和值?

最佳答案

您正在使用 getattrsetattr以错误的方式。实际签名如下:

variable = object.field  ~  variable = getattr(object, 'field' [, default])
object.field = value     ~  setattr(object, 'field', value)

关于Python如何将属性添加到函数中的现有对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31620772/

相关文章:

python - 返回到循环的顶部

python - 如何使用 Ajax 将表中的数据发布到 Flask View ?

javascript - 如何将剪贴板内容自动粘贴到我的网页中

python - 将 dockerfile 从目录配置为 'read'?

python - 单元测试 flask flask.g

javascript - 如何打开包含用 javascript 编写的图形的弹出窗口?

python - 错误 fabs(sc) > DBL_EPSILON 在函数 cvFindExtrinsicCameraParams2 中意味着什么?

python - 从 CSV 文件中获取值列表

python - TypeError : array( ['cycling' ], dtype=object) 不可 JSON 序列化

python - 端点可以忽略 Flask 中的 'after request' 装饰器吗?