기본적으로 유형을 지원하지 않는 기록을 파이썬 이유는 무엇입니까? # 39 의 it& 갖는 것은 mutable 버전이 네메트루프레.
'내가' namedtuple._replace 사용할 수 있습니다. 하지만 꼭 이 기록은 이후 ',' 난 또 다른 인스턴스입니다 tcpg namedtuple._replace 모음과 모음 과도한 되는 수정할 필요가 있습니다.
Background: I have a 디바이스에는 데릭쉐퍼드와 속성을 가진 it 폴링하여 TCP / IP 를 통해 얻을 수 있습니다. 즉, 해당 표현을 mutable) 는 객체.
편집: 나는 누구를 위한 일련의 디바이스에는 데릭쉐퍼드와 폴링할.
편집: 데릭쉐퍼드와 객체에는 디스플레이하여 파이크스 를 사용하여 속성뿐 반복할 수 있다. 저도 같은 특별한 방법을 추가할 수 있지만, '와' '' getitem iter 그런이야길 있으면 쉽게.
편집: 내가 선호하는 그 속성 유형 (것처럼 are in my 장치) 가 고정되어 있지만, mutable).
이 같은 일이 말인가요?
class Record(object):
__slots__= "attribute1", "attribute2", "attribute3",
def items(self):
"dict style items"
return [
(field_name, getattr(self, field_name))
for field_name in self.__slots__]
def __iter__(self):
"iterate over fields tuple/list style"
for field_name in self.__slots__:
yield getattr(self, field_name)
def __getitem__(self, index):
"tuple/list style getitem"
return getattr(self, self.__slots__[index])
>>> r= Record()
>>> r.attribute1= "hello"
>>> r.attribute2= "there"
>>> r.attribute3= 3.14
>>> print r.items()
[('attribute1', 'hello'), ('attribute2', 'there'), ('attribute3', 3.1400000000000001)]
>>> print tuple(r)
('hello', 'there', 3.1400000000000001)
참고로 메서드을 단 한 번의 샘플을 제공할 수 있는 방법.
['티페스자심렌임스파스'] 사용할 수 있습니다 (http://docs.python.org/py3k/library/types.html # 티페스자심렌임스파스):
>>> import types
>>> r= types.SimpleNamespace()
>>> r.attribute1= "hello"
>>> r.attribute2= "there"
>>> r.attribute3= 3.14
'디렉터 (r)' 다시그것들을 고객님께 속성용 이름 (필터링부터 아웃해야 오스타츠비트 (_" ";) ',' 모든 물론).
또한 클래스 인스턴스 (디스크입니다. diskid 좋은 속성용 액세스만 구문) 사용할 수도 있습니다. "만약 slots 프로파일링하려는 않도록 dict 사용할 수 있습니다 'a' '생성되는가 인스턴스별로.
업데이트:
이후 그렇게 중요하다고 주문하십시오 너회의 책정안 (및 운영까지도 반복할 수 모든 속성) 승인/보류 '' 오르데레디스 길을 갈 것으로 보인다. 파이썬 표준 '모음' 모듈에서는 vmware. 2.7 이 포함되어 있다. 이외에도 인터넷, 파이썬 < 주변에 부동 구축 2.7.
마치 하위 특성 스타일 액세스만 추가할 수 있습니다.
from collections import OrderedDict
class MutableNamedTuple(OrderedDict):
def __init__(self, *args, **kwargs):
super(MutableNamedTuple, self).__init__(*args, **kwargs)
self._initialized = True
def __getattr__(self, name):
try:
return self[name]
except KeyError:
raise AttributeError(name)
def __setattr__(self, name, value):
if hasattr(self, '_initialized'):
super(MutableNamedTuple, self).__setitem__(name, value)
else:
super(MutableNamedTuple, self).__setattr__(name, value)
그럼 할 수 있다.
>>> t = MutableNamedTuple()
>>> t.foo = u'Crazy camels!'
>>> t.bar = u'Yay, attribute access'
>>> t.foo
u'Crazy camels!'
>>> t.values()
[u'Crazy camels!', u'Yay, attribute access']
패키지 홈: http://pypi.python.org/pypi/recordtype
단순한 예:
from recordtype import recordtype
Person = recordtype('Person', 'first_name last_name phone_number')
person1 = Person('Trent', 'Steele', '637-3049')
person1.last_name = 'Terrence';
print person1
# Person(first_name=Trent, last_name=Terrence, phone_number=637-3049)
간단한 기본값입니다 예:
Basis = recordtype('Basis', [('x', 1), ('y', 0)])
필드 (,, person1< 반복할 < code> /code>. (clarification):
map(person1.__getattribute__, Person._fields)
이 질문에 중복 [다른 하나는] [1]. 레코드클레스 '-' 콜레스티언스트남드투플레 변경 가능 대안이 될 수 있습니다.
It 는 API 와 동일한 메모리 공간 '로 네메트루프레' (실제로는 또한 빠름). It 지원부에 지정. 예를 들면 다음과 같습니다.
from recordclass import recordclass
Point = recordclass('Point', 'x y')
>>> p = Point(1, 2)
>>> p
Point(x=1, y=2)
>>> print(p.x, p.y)
1 2
>>> p.x += 2; p.y += 3; print(p)
Point(x=3, y=5)
어디 그뿐인가 완료하십시오 예 (또한 포함시키십시오 성능 비교).
[1]: # 29419745 https://stackoverflow.com/questions/29290359/existence-of-mutable-named-tuple-in-python/29419745
밀접한 관련이 있는 [존재를 release. 튜플 mutable) 의 파이썬?] (https://stackoverflow.com/q/29290359/341970) 질문 '대안' 네메트루프레 비교하기 위해 사용되는 6 13 테스트를 변경 가능.
['레코드클레스'] 은 이러한 테스트에 따르면 두 번째 베스트 후보 (https://pypi.python.org/pypi/recordclass) 가 캜 확장자입니다. 물론, 그것은 요구 사항에 따라 서버인지에 캜 확장명은 방관하겠나 선호하고 있다.
특히 brocade. com/support/service_plans. 테스트를 참조 [mutable) 의 존재를 release. 튜플 파이썬?] (https://stackoverflow.com/q/29290359/341970)
이것은 이 같은 동작을 완전히 호환됩니까 목록 및 변경 가능 완료하십시오 네메트루프레 I made it.
class AbstractNamedArray():
"""a mutable collections.namedtuple"""
def __new__(cls, *args, **kwargs):
inst = object.__new__(cls) # to rename the class
inst._list = len(cls._fields)*[None]
inst._mapping = {}
for i, field in enumerate(cls._fields):
inst._mapping[field] = i
return inst
def __init__(self, *args, **kwargs):
if len(kwargs) == 0 and len(args) != 0:
assert len(args) == len(self._fields), 'bad number of arguments'
self._list = list(args)
elif len(args) == 0 and len(kwargs) != 0:
for field, value in kwargs.items():
assert field in self._fields, 'field {} doesn\'t exist'
self._list[self._mapping[field]] = value
else:
raise ValueError("you can't mix args and kwargs")
def __getattr__(self, x):
return object.__getattribute__(self, '_list')[object.__getattribute__(self, '_mapping')[x]]
def __setattr__(self, x, y):
if x in self._fields:
self._list[self._mapping[x]] = y
else:
object.__setattr__(self, x, y)
def __repr__(self):
fields = []
for field, value in zip(self._fields, map(self.__getattr__, self._fields)):
fields.append('{}={}'.format(field, repr(value)))
return '{}({})'.format(self._name, ', '.join(fields))
def __iter__(self):
yield from self._list
def __list__(self):
return self._list[:]
def __len__(self):
return len(self._fields)
def __getitem__(self, x):
return self._list[x]
def __setitem__(self, x, y):
self._list[x] = y
def __contains__(self, x):
return x in self._list
def reverse(self):
self._list.reverse()
def copy(self):
return self._list.copy()
def namedarray(name, fields):
"""used to construct a named array (fixed-length list with named fields)"""
return type(name, (AbstractNamedarray,), {'_name': name, '_fields': fields})
이 같은 일이 '할 수 있는' dict 자체 딕트 '클래스'. 기본적인 개념은 동일하게 스티브 스테이트 의 [타르치] (http://code.activestate.com/recipes/576972-attrdict/) 레시피, 그러나 구현은 간단해진다는. 그 결과, mutable) 가 모두 instance& # 39 의 특성 때문에 좀 더 필요한 것, 그 값을 변경할 수 있다. 비록 속성뿐 aren& # 39, t 순서화된 및 / 또는 그 값을 현재 수준들과 반복할 수 있습니다.
class Record(dict):
def __init__(self, *args, **kwargs):
super(Record, self).__init__(*args, **kwargs)
self.__dict__ = self