2013-09-24 52 views
1

我在想如果有一些方法來解壓對象屬性。 通常這樣做涉及到一系列的:在Python中解壓對象變量

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

但是應該可以做的更好。

我想是這樣的:

def __init__(self,x,y,z): 
    self.(x,y,z) = x,y,z 

或可能:

與X,Y,Z的解壓縮(個體經營)

,甚至類似的功能:

def __init__(self,x,y,z): 
    unpack(self,x,y,z) 

任何想法?還是有更多pythonic的方式來做到這一點?

+4

'的名稱( 'x','y','z'):setattr(self,name,locals()[name])' – falsetru

+0

做什麼問題這是正常的方式? –

+0

如果在對象的屬性中有可預測的模式,則表示您應該創建一個詞典來收集這些值,並使用getter方法來訪問它們。編寫不可預測的屬性是人類應該做的。 – Mai

回答

3

您可能需要使用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不過是一個普通班,你可以創建一個繼承它的類。

+0

這是從這裏複製和粘貼:http://docs.python.org/2/library/collections.html#collections.namedtuple – Mai

+0

謝謝你添加源回來:) – Mai

0

我敢肯定,你可以這樣做: self.x,self.y,self.z = X,Y,Z