2013-09-24 3 views
1

객체 속성을 언팩하는 방법이 있다면 생각 중입니다. 더 잘 할 수 있어야한다 그러나파이썬에서 객체 변수 풀기

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) 

아이디어가 있으십니까? 아니면 이것을하기위한 좀 더 파이썬적인 방법이 있습니까?

+4

'= X, Y self.x, self.y로, self.z을 ('x', 'y', 'z') : setattr (self, name, locals() [name])' – falsetru

+0

그것은 정상적인 방법입니까? –

+0

개체의 특성에 예측 가능한 패턴이있는 경우 해당 값을 수집하기위한 dict 및 해당 개체에 액세스하는 getter 메서드를 만들어야 함을 의미합니다. 예측 불가능한 속성을 쓰는 것은 인간이해야하는 것입니다. – Mai

답변

3

당신은 정확하게 당신이 원하는 것은 수행하는 namedtuple을 사용할 수 있습니다 :

코드 예제 공식에서 파이썬 문서는 :

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') 
:

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

위의 코드에 해당합니다

사용 방법은 다음과 같습니다.

>>> 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

당신이 할 수 있다고 확신 여기 설명 :에, 이름 Z

관련 문제