在Python中解包对象变量

10

我在思考是否有一种方法可以拆开对象属性。

通常情况下,这涉及到一系列的操作:

self.x = x
self.y = y
... #etc.

然而,应该有更好的方法。

我在考虑类似于以下的方式:

def __init__(self,x,y,z):
  self.(x,y,z) = x,y,z
或者:
使用 x、y 和 z 反包装(unpack)self,
或者甚至像这样的函数:
def __init__(self,x,y,z):
  unpack(self,x,y,z)

有什么想法吗?或者有没有更Pythonic的方法来做到这一点?


4
for name in ('x','y','z'): setattr(self, name, locals()[name]) - falsetru
1
用正常的方式做有什么问题吗? - Burhan Khalid
如果您的对象属性具有可预测的模式,那么应该创建一个字典来收集这些值,并编写一个getter方法来访问它们。编写不可预测的属性是人类应该做的事情。 - Patrick the Cat
而且你可以解包任何字典。 - Patrick the Cat
4个回答

4
你可能想要使用namedtuple,它正好做你想要的事情:

官方 Python 文档中的代码示例:

Point = namedtuple('Point', ['x', 'y'], verbose=True)

上面的代码等同于:
class Point(tuple):
    'Point(x, y)'

    __slots__ = ()

    _fields = ('x', 'y')

    def __new__(_cls, x, y):
        'Create a new instance of Point(x, y)'
        return _tuple.__new__(_cls, (x, y))

    @classmethod
    def _make(cls, iterable, new=tuple.__new__, len=len):
        'Make a new Point object from a sequence or iterable'
        result = new(cls, iterable)
        if len(result) != 2:
            raise TypeError('Expected 2 arguments, got %d' % len(result))
        return result

    def __repr__(self):
        'Return a nicely formatted representation string'
        return 'Point(x=%r, y=%r)' % self

    def _asdict(self):
        'Return a new OrderedDict which maps field names to their values'
        return OrderedDict(zip(self._fields, self))

    def _replace(_self, **kwds):
        'Return a new Point object replacing specified fields with new values'
        result = _self._make(map(kwds.pop, ('x', 'y'), _self))
        if kwds:
            raise ValueError('Got unexpected field names: %r' % kwds.keys())
        return result

    def __getnewargs__(self):
        'Return self as a plain tuple.   Used by copy and pickle.'
        return tuple(self)

    __dict__ = _property(_asdict)

    def __getstate__(self):
        'Exclude the OrderedDict from pickling'
        pass

    x = _property(_itemgetter(0), doc='Alias for field number 0')

    y = _property(_itemgetter(1), doc='Alias for field number 1')

以下是如何使用它的方法:
>>> p = Point(11, y=22)     # instantiate with positional or keyword arguments
>>> p[0] + p[1]             # indexable like the plain tuple (11, 22)
33
>>> x, y = p                # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y               # fields also accessible by name
33
>>> p                       # readable __repr__ with a name=value style
Point(x=11, y=22)

来源: http://docs.python.org/2/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields

值得一提的是,namedtuple 只是一个普通的类,你可以创建一个继承自它的类。


这是从这里复制并粘贴的:http://docs.python.org/2/library/collections.html#collections.namedtuple - Patrick the Cat

2

我非常确定你可以这样做:

self.x, self.y, self.z = x, y, z


0

-1
class Blahblah:
def __init__(self, *args, **kwargs):
    def unpack(vars_name, args, kwargs): #Cant be acceded for some instance in this place
        nonlocal self
        for i, var in enumerate(vars_name):
            exec(f"self.{var}={args[i]}")
        for key, value in kwargs.items():
            exec(f"self.{key}={value}")
    
    #You must add some validator for de length of args before the next code in this place
    
    vars_for_self = ["a","b","c"]
    unpack(vars_for_self, args, kwargs)
    
    del vars_for_self, args, kwargs, unpack #For clean vars in the class instance
            
    

    #First ways to check de self vars creation
    #print(self.__dict__)

    #Second way to check
    #print(locals()["self"].__dict__)

#Your other methods go here

签到结果

if __name__== "__main__":
#And the last way
  c = Blahblah(3,4,5, x=6,y=7,z=0)
  #print(c.a)
  #print(c.x)

  print(c.__dict__)
  print(vars(Blahblah.__dict__["__init__"]))

这段代码存在漏洞,当值不可信时,可能会导致任意代码执行,因此不应使用。x = "someVar"; y="1; import os; os.system('/bin/bash')"; exec(f"{x}={y}")exec() 和 eval() 是危险的函数,不应使用。getattr() 和 setattr() 是更好的选择,但出于类似的原因,也应该避免使用。 - testUser12

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接