programing

SimpleNamespace와 빈 클래스 정의의 차이점은 무엇입니까?

easyjava 2023. 6. 3. 08:51
반응형

SimpleNamespace와 빈 클래스 정의의 차이점은 무엇입니까?

다음은 어느 쪽이든 작동하는 것 같습니다.장점은 무엇입니까(좋은 것 외에).repr) 사용의types.SimpleNamespace아니면 같은 건가요?

>>> import types
>>> class Cls():
...     pass
... 
>>> foo = types.SimpleNamespace() # or foo = Cls()
>>> foo.bar = 42
>>> foo.bar
42
>>> del foo.bar
>>> foo.bar
AttributeError: 'types.SimpleNamespace' object has no attribute 'bar'

이는 유형 모듈 설명에 잘 설명되어 있습니다.그것은 당신에게 보여줍니다.types.SimpleNamespace이는 대략 다음과 같습니다.

class SimpleNamespace:
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)

    def __repr__(self):
        keys = sorted(self.__dict__)
        items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys)
        return "{}({})".format(type(self).__name__, ", ".join(items))

    def __eq__(self, other):
        return self.__dict__ == other.__dict__

빈 클래스에 비해 다음과 같은 이점이 있습니다.

  1. 개체를 구성하는 동안 속성을 초기화할 수 있습니다.sn = SimpleNamespace(a=1, b=2)
  2. 가독성을 제공합니다.repr():eval(repr(sn)) == sn
  3. 기본 비교를 재정의합니다.비교하는 대신id()대신 속성 값을 비교합니다.

A에서는 속성만 포함할 수 있는 개체를 인스턴스화하는 메커니즘을 제공합니다.사실상, 그것은 공상가가 있는 빈 수업입니다.__init__()그리고 도움이 되는__repr__():

>>> from types import SimpleNamespace
>>> sn = SimpleNamespace(x = 1, y = 2)
>>> sn
namespace(x=1, y=2)
>>> sn.z = 'foo'
>>> del(sn.x)
>>> sn
namespace(y=2, z='foo')

또는

from types import SimpleNamespace

sn = SimpleNamespace(x = 1, y = 2)
print(sn)

sn.z = 'foo'
del(sn.x)
print(sn)

출력:

namespace(x=1, y=2)
namespace(y=2, z='foo')

대답도 도움이 될 수 있습니다.

언급URL : https://stackoverflow.com/questions/37161275/what-is-the-difference-between-simplenamespace-and-empty-class-definition

반응형