根据后缀从函数返回不同的值

2024-10-06 07:09:59 发布

您现在位置:Python中文网/ 问答频道 /正文

类似于类,但也应该在类内工作。我不确定是否可能,也不确定要搜索的关键字是否正确,因此如果已经有答案,我深表歉意。你知道吗

例如,我的意思是像这样-

def location():
    x = 5
    y = 0
    z = 0
    return x,y,z

然后输入location().x,得到数字5。在我看来,用location().x而不是location()[0]要好得多。你知道吗

编辑:我要求的是这种方式,而不是类,因为您可能希望将它放在类中,比如objectInfo( object ).getLocation().x


Tags: 答案编辑returnobjectdef方式数字location
3条回答

您可以使用"bunch"

>>> class Bunch(object):
...     def __init__(self, **kwargs):
...             self.__dict__.update(kwargs)
... 
>>> def location():
...     return Bunch(x=5, y=0, z=0)
... 
>>> location().x
5
>>> location().y
0
>>> 

使用^{}

>>> from collections import namedtuple
>>>
>>> XYZ = namedtuple('XYZ', ['x', 'y', 'z'])
>>>
>>> def location():
...     return XYZ(5, 0, 0)
...
>>> location().x
5

使用namedtuple,仍然可以使用索引[..]访问值:

>>> location()[0]
5

更新

如果使用Python 3.3+,还可以使用^{}

>>> from types import SimpleNamespace
>>> def location():
...     return SimpleNamespace(x=5, y=0, z=0)
...
>>> location().x
5

否则,使用以下类(来自上面的SimpleNamespace链接):

class SimpleNamespace:
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)
    def __repr__(self):
        keys = sorted(self.__dict__)
        items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys)
        return "{}({})".format(type(self).__name__, ", ".join(items))
    def __eq__(self, other):
        return self.__dict__ == other.__dict__

你可以把它当作矩阵

定义(x,y,z): x=1 y=7 z=10`` 返回A=[x,y,z]

在你可以用这种方法得到numpers之后,A[1]代表x。 我想你明白我的意思,这是一种把变量连成一个序列的方法

相关问题 更多 >