Python中通过字符串变量设置和获取@property方法

2024-02-06

目前,我有一个通用函数,您可以在其中传递属性名称和类(它也适用于特定对象实例,但我正在使用类),并且该函数将通过调用来查找并操作该属性

getattr(model_class, model_attribute)

它将通过调用(这次是在对象实例上)来修改属性

settattr(模型_obj,键,值)

然而,我有一堂课,我们有一个@property定义方法而不是简单的属性,并且setattr不起作用。如何动态获取@property基于该属性方法的字符串名称?

也许我可以用__dict__但这看起来很脏而且不那么安全。

编辑:示例代码

广义函数

def process_general(mapping, map_keys, model_class, filter_fn, op_mode=op_modes.UPDATE):
    """
    Creates or updates a general table object based on a config dictionary.

    `mapping`: a configuration dictionary, specifying info about the table row value
    `map_keys`: keys in the mapping that we use for the ORM object
    `model_class`: the ORM model class we use the config data in
    `op_mode`: the kind of operation we want to perform (delete, update, add, etc.)

    Note that relationships between model objects must be defined and connected
    outside of this function.
    """
    # We construct a dictionary containing the values we need to set
    arg_dict = make_keyword_args(map_keys, mapping)

    # if we are updating, then we must first check if the item exists
    # already
    if (op_mode == op_modes.UPDATE):
        # Find all rows that match by the unique token.
        # It should only be one, but we will process all of them if it is the
        # case that we didn't stick to the uniqueness requirement.
        matches = filter_fn()

        # Keep track of the length of the iterator so we know if we need to add
        # a new row
        num_results = 0
        for match in matches:
            # and we set all of the object attributes based on the dictionary
            set_attrs_from_dict(match, arg_dict)
            model_obj = match
            num_results += 1
        # We have found no matches, so just add a new row
        if (num_results < 1):
            model_obj = model_class(**arg_dict)

        return model_obj

    # TODO add support for other modes. This here defaults to add
    else:
        return model_class(**arg_dict)

传入的示例类:

class Dataset(db.Model, UserContribMixin):
    # A list of filters for the dataset. It can be built into the dataset filter form dict
    # in get_filter_form. It's also useful for searching.
    filters     = db.relationship('DatasetFilter', backref='dataset')

    # private, and retrieved from the @property = select
    _fact_select = db.relationship('DatasetFactSelect', order_by='DatasetFactSelect.order')

    @property
    def fact_select(self):
        """
        FIXME: What is this used for?

        Appears to be a list of strings used to select (something) from the
        fact model in the star dataset interface.

        :return: List of strings used to select from the fact model
        :rtype: list
        """

        # these should be in proper order from the relationship order_by clause
        sels = [sel.fact_select for sel in self._fact_select]
        return sels

Calling getattr(model_class, model_attribute)将返回属性对象model_attribute指。我假设您已经知道这一点并且正在尝试访问属性对象的值。

class A(object):

    def __init__(self):
        self._myprop = "Hello"

    @property
    def myprop(self):
        return self._myprop

    @myprop.setter
    def myprop(self, v):
        self._myprop = v

prop = getattr(A, "myprop")

print prop
# <property object at 0x7fe1b595a2b8>

现在我们已经从类中获取了属性对象,我们想要访问它的值。属性有3个方法fget, fset, and fdel提供对getter, settter, and deleter为该属性定义的方法。

Since myprop是一个实例方法,我们必须创建一个实例才能调用它。

print prop.fget
# <function myprop at 0x7fe1b595d5f0>

print prop.fset
# <function myprop at 0x7fe1b595d668>

print prop.fdel  # We never defined a deleter method
# None

a = A()
print prop.fget(a)
#  Hello
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python中通过字符串变量设置和获取@property方法 的相关文章

  • Google App Engine queue.yaml 无法在开发服务器中工作

    我无法让 dev appserver py 识别我使用queue yaml 创建的自定义队列 他们没有出现在http localhost 8000 taskqueue http localhost 8000 taskqueue 当我尝试向其
  • scipy 将一个稀疏矩阵的所有行附加到另一个稀疏矩阵

    我有一个 numpy 矩阵 想在其中附加另一个矩阵 这两个矩阵的形状为 m1 shape 2777 5902 m2 shape 695 5902 我想将 m2 附加到 m1 以便新矩阵的形状为 m new shape 3472 5902 当
  • Twisted 的 Deferred 和 JavaScript 中的 Promise 一样吗?

    我开始在一个需要异步编程的项目中使用 Twisted 并且文档非常好 所以我的问题是 Twisted 中的 Deferred 与 Javascript 中的 Promise 相同吗 如果不是 有什么区别 你的问题的答案是Yes and No
  • Pandas:GroupBy 到 DataFrame

    参考这个关于 groupby 到 dataframe 的非常流行的问题 https stackoverflow com questions 10373660 converting a pandas groupby object to dat
  • 如何检查python xlrd库中的excel文件是否有效

    有什么办法与xlrd库来检查您使用的文件是否是有效的 Excel 文件 我知道还有其他库可以检查文件头 我可以使用文件扩展名检查 但为了多平台性我想知道是否有任何我可以使用的功能xlrd库本身在尝试打开文件时可能会返回类似 false 的内
  • Mac OS X 中文件系统的 Unicode 编码在 Python 中不正确?

    在 OS X 和 Python 中处理 Unicode 文件名有点困难 我试图在代码中稍后使用文件名作为正则表达式的输入 但文件名中使用的编码似乎与 sys getfilesystemencoding 告诉我的不同 采取以下代码 usr b
  • Python 中的流式传输管道

    我正在尝试使用 Python 将 vmstat 的输出转换为 CSV 文件 因此我使用类似的方法转换为 CSV 并将日期和时间添加为列 vmstat 5 python myscript py gt gt vmstat log 我遇到的问题是
  • 工作日重新订购 Pandas 系列

    使用 Pandas 我提取了一个 CSV 文件 然后创建了一系列数据来找出一周中哪几天崩溃最多 crashes by day bc DAY OF WEEK value counts 然后我将其绘制出来 但当然它按照与该系列相同的排名顺序绘制
  • 没有名为 StringIO 的模块

    我有Python 3 6 我想从另一个名为 run py 的 python 文件执行名为 operation py 的 python 文件 In operation py I do from cStringIO import StringI
  • 在 matplotlib 中的极坐标图上移动径向刻度标签

    From matplotlib 示例 http matplotlib org examples pylab examples polar demo html import numpy as np import seaborn as sbs
  • 从扫描文档中提取行表 opencv python

    我想从扫描的表中提取信息并将其存储为 csv 现在我的表提取算法执行以下步骤 应用倾斜校正 应用高斯滤波器进行去噪 使用 Otsu 阈值进行二值化 进行形态学开局 Canny 边缘检测 进行霍夫变换以获得表格行 去除重复行 10像素范围内相
  • 使用 python 绘制正值小提琴图

    我发现小提琴图信息丰富且有用 我使用 python 库 seaborn 然而 当应用于正值时 它们几乎总是在低端显示负值 我发现这确实具有误导性 尤其是在处理现实数据集时 在seaborn的官方文档中https seaborn pydata
  • Matplotlib 中 x 轴标签的频率和旋转

    我在下面编写了一个简单的脚本来使用 matplotlib 生成图形 我想将 x tick 频率从每月增加到每周并轮换标签 我不知道从哪里开始 x 轴频率 我的旋转线产生错误 TypeError set xticks got an unexp
  • 将seaborn.palplot轴添加到现有图形中以可视化不同调色板

    将seaborn人物添加到子图中是usually https seaborn pydata org examples cubehelix palette html创建图形时通过传递 ax 来完成 例如 sns kdeplot x y cma
  • 在 keras 中保存和加载权重

    我试图从我训练过的模型中保存和加载权重 我用来保存模型的代码是 TensorBoard log dir output model fit generator image a b gen batch size steps per epoch
  • SocketIO + Flask 检测断开连接

    我在这里有一个不同的问题 但意识到它可以简化为 如何检测客户端何时从页面断开连接 关闭其页面或单击链接 换句话说 套接字连接关闭 我想制作一个带有更新用户列表的聊天应用程序 并且我在 Python 上使用 Flask 当用户连接时 浏览器发
  • 混淆矩阵不支持多标签指示符

    multilabel indicator is not supported是我在尝试运行时收到的错误消息 confusion matrix y test predictions y test is a DataFrame其形状为 Horse
  • 如何根据第一列创建新列,同时考虑Python Pandas中字母和列表的大小? [复制]

    这个问题在这里已经有答案了 我在 Python Pandas 中有 DataFrame 如下所示 col1 John Simon prd agc Ann White BeN and Ann bad list Ben Wayne 我需要这样做
  • 将上下文管理器的动态可迭代链接到单个 with 语句

    我有一堆想要链接的上下文管理器 第一眼看上去 contextlib nested看起来是一个合适的解决方案 但是 此方法在文档中被标记为已弃用 该文档还指出最新的with声明直接允许这样做 自 2 7 版起已弃用 with 语句现在支持此
  • 使用ssl和socket的python客户端身份验证

    我有一个 python 服务器 需要客户端使用证书进行身份验证 我如何制作一个客户端脚本 使用客户端证书由 python 中的服务器使用 ssl 和套接字模块进行身份验证 有没有仅使用套接字和 ssl 而不扭曲的示例 from OpenSS

随机推荐