Python에서 빈 개체 만들기
파이썬에서 빈 객체를 정의하기위한 바로 가기가 있습니까? 아니면 항상 사용자 정의 빈 클래스의 인스턴스를 만들어야합니까?
편집 : 오리 타이핑에 사용할 수있는 빈 개체를 의미합니다.
type을 사용하여 즉석에서 새 클래스를 만든 다음 인스턴스화 할 수 있습니다. 이렇게 :
>>> t = type('test', (object,), {})()
>>> t
<__main__.test at 0xb615930c>
유형에 대한 인수는 클래스 이름, 기본 클래스의 튜플 및 개체의 사전입니다. 함수 (객체의 메서드) 또는 속성을 포함 할 수 있습니다.
실제로 첫 번째 줄을 줄여서
>>> t = type('test', (), {})()
>>> t.__class__.__bases__
(object,)
기본적으로 type은 object에서 상속하는 새로운 스타일 클래스를 생성하기 때문입니다.
type
메타 프로그래밍을 위해 파이썬에서 사용됩니다 .
그러나 객체의 인스턴스를 만들고 싶다면. 그런 다음 인스턴스를 만듭니다. lejlot이 제안한 것처럼.
이와 같은 새 클래스의 인스턴스를 만드는 데 유용 할 수있는 중요한 차이점이 있습니다.
>>> a = object()
>>> a.whoops = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'whoops'
어디에 :
>>> b = type('', (), {})()
>>> b.this_works = 'cool'
>>>
예, Python 3.3에서 SimpleNamespace 가 추가되었습니다.
객체와 달리 SimpleNamespace를 사용하면 속성을 추가하고 제거 할 수 있습니다. SimpleNamespace 개체가 키워드 인수로 초기화되면 기본 네임 스페이스에 직접 추가됩니다.
예:
import types
x = types.SimpleNamespace()
x.happy = True
print(x.happy) # True
del x.happy
print(x.happy) # AttributeError. object has no attribute 'happy'
빈 (-ish) 객체를 생성하는 간단하고 덜 무서운 방법 중 하나는 함수가 Lambda 함수를 포함하여 Python의 객체라는 사실을 이용하는 것입니다.
obj = lambda: None
obj.test = "Hello, world!"
예를 들면 :
In [18]: x = lambda: None
In [19]: x.test = "Hello, world!"
In [20]: x.test
Out[20]: 'Hello, world!'
"빈 개체"란 무엇을 의미합니까? 클래스의 인스턴스 object
? 간단히 실행할 수 있습니다.
a = object()
아니면 널 참조에 대한 초기화를 의미합니까? 그런 다음 사용할 수 있습니다
a = None
제안 된 모든 솔루션이 다소 어색합니다.
나는 해키가 아니지만 실제로 원래 디자인에 따르는 방법을 찾았습니다.
>>> from mock import Mock
>>> foo = Mock(spec=['foo'], foo='foo')
>>> foo.foo
'foo'
>>> foo.bar
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/prezi/virtualenv/local/lib/python2.7/site-packages/mock/mock.py", line 698, in __getattr__
raise AttributeError("Mock object has no attribute %r" % name)
AttributeError: Mock object has no attribute 'bar'
See the documentation of unittest.mock here.
Constructs a new empty Set object. If the optional iterable parameter is supplied, updates the set with elements obtained from iteration. All of the elements in iterable should be immutable or be transformable to an immutable using the protocol described in section Protocol for automatic conversion to immutable.
Ex:
myobj = set()
for i in range(1,10): myobj.add(i)
print(myobj)
참고URL : https://stackoverflow.com/questions/19476816/creating-an-empty-object-in-python
'Program Tip' 카테고리의 다른 글
Groovy 내장 REST / HTTP 클라이언트? (0) | 2020.11.22 |
---|---|
ASP.NET에서 현재 도메인 이름을 얻는 방법 (0) | 2020.11.22 |
헤드폰이 연결되어 있습니까? (0) | 2020.11.22 |
ScrollView 내의 이미지 그리드 (0) | 2020.11.22 |
@Override를 사용하여 "수퍼 클래스 메서드를 재정의해야 함"이 표시되는 이유는 무엇입니까? (0) | 2020.11.22 |