带有“指针”的Python函数

发布于 2024-10-25 05:22:31 字数 1468 浏览 2 评论 0原文

好吧,我最近开始用 Python 编程,我真的很喜欢它。

但是,我遇到了一个小问题。

我希望能够定义一个函数来接收一些数据并将其分配给我指定的变量,而不是每次要提交值时都必须执行该操作。

这是一个代码片段:

       try:
            if elem.virtual.tag:
                virt = True
                temp_asset.set_virtual(True)
        except AttributeError:
            temp_asset.set_virtual(False)
        if virt: #if virtual, get only faction, value, and range for presence
            try:
                fac = elem.presence.faction #an xml tag (objectified)
            except AttributeError:
                fac = "faction tag not found"
                temp_asset.misload = True
            try:
                val = elem.presence.value
            except AttributeError:
                val = "value tag not found"
                temp_asset.misload = True
            try:
                rang = elem.presence.range
            except AttributeError:
                rang = "range tag not found"
                temp_asset.misload = True
            #Set presence values
            temp_asset.set_presence(fac, val, rang)

函数设置值,但我希望能够使用如下内容执行错误检查:

def checkval(self, variable_to_set, tag_to_use)
    try:
         variable_to_set = tag_to_use
    except AttributeError:
         variable_to_set = "tag not found"
         temp_asset.misload = True

这可行吗?如果我需要显示更多代码,请告诉我。

编辑:我本身不需要指针,只需要任何以这种方式工作并节省打字的东西。

编辑2:或者,我需要一个如何检查对象化xml节点是否存在(lxml)的解决方案。

Ok, I recently started programming in Python, and I really like it.

However, I have run into a little issue.

I want to be able to define a function to take in some data and assign it to a variable that I designate, rather than have to perform the operation every time I want to submit the value.

Here is a code fragment:

       try:
            if elem.virtual.tag:
                virt = True
                temp_asset.set_virtual(True)
        except AttributeError:
            temp_asset.set_virtual(False)
        if virt: #if virtual, get only faction, value, and range for presence
            try:
                fac = elem.presence.faction #an xml tag (objectified)
            except AttributeError:
                fac = "faction tag not found"
                temp_asset.misload = True
            try:
                val = elem.presence.value
            except AttributeError:
                val = "value tag not found"
                temp_asset.misload = True
            try:
                rang = elem.presence.range
            except AttributeError:
                rang = "range tag not found"
                temp_asset.misload = True
            #Set presence values
            temp_asset.set_presence(fac, val, rang)

The functions set the values, but I want to be able to perform the error checking with something like this:

def checkval(self, variable_to_set, tag_to_use)
    try:
         variable_to_set = tag_to_use
    except AttributeError:
         variable_to_set = "tag not found"
         temp_asset.misload = True

Is this doable? Let me know if I need to show more code.

Edit: I don't need pointers per se, just anything that works this way and saves typing.

Edit 2: Alternatively, I need a solution of how to check whether an objectified xml node exists (lxml).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

远山浅 2024-11-01 05:22:32

您是否尝试/查看过 getattr 和 < a href="http://docs.python.org/library/functions.html#setattr" rel="nofollow">setattr 函数?

例如,假设这些“变量”是对象属性:

def checkval(self, attr, presence, tagstr):
    tag = getattr(presence, tagstr, None)           # tag = presence."tagstr" or None
    setattr(self, attr, tag or 'tag not found')     # ?? = presence."tagstr" or 'tag not found'     
    if tag is None:
        self.temp_asset.misload = True   

您可以这样称呼它,

your_object.checkval('fac', elem.presence, 'faction')

或者,您可以在尝试查找标签之前预先定义这些变量并设置它们的默认值。例如:

class YourObject(object):
    _attrmap = {
        'fac': 'faction',
        'val': 'value',
        'rang': 'range',
    }

    def __init__(self):
        # set default values
        for attr, tagstr in self._attrmap.items():
            setattr(self, attr, '%s tag not found' % tagstr)

    def checkval(self, attr, presence):
        for attr, tagstr in self._attrmap.items():
            tag = getattr(presence, tagstr, None)
            if tag is not None:
                setattr(self, attr, tag)
            else:
                self.temp_asset.misload = True

Have you tried/looked into the getattr and setattr functions?

For example, assuming these "variables" are object attributes:

def checkval(self, attr, presence, tagstr):
    tag = getattr(presence, tagstr, None)           # tag = presence."tagstr" or None
    setattr(self, attr, tag or 'tag not found')     # ?? = presence."tagstr" or 'tag not found'     
    if tag is None:
        self.temp_asset.misload = True   

You call it like,

your_object.checkval('fac', elem.presence, 'faction')

Alternatively, you can pre-define these variables and set them default values before you attempt to look up the tags. For example:

class YourObject(object):
    _attrmap = {
        'fac': 'faction',
        'val': 'value',
        'rang': 'range',
    }

    def __init__(self):
        # set default values
        for attr, tagstr in self._attrmap.items():
            setattr(self, attr, '%s tag not found' % tagstr)

    def checkval(self, attr, presence):
        for attr, tagstr in self._attrmap.items():
            tag = getattr(presence, tagstr, None)
            if tag is not None:
                setattr(self, attr, tag)
            else:
                self.temp_asset.misload = True
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文