Hướng dẫn dùng python simplenamespace python

The following seems to work either way. What is the advantage (other than the nice repr) of using types.SimpleNamespace? Or is it the same thing?

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

asked May 11, 2016 at 11:28

BaruchBaruch

19.6k23 gold badges123 silver badges195 bronze badges

0

This is explained pretty well in the types module description. It shows you that types.SimpleNamespace is roughly equivalent to this:

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__

This provides the following advantages over an empty class:

  1. It allows you to initialize attributes while constructing the object: sn = SimpleNamespace(a=1, b=2)
  2. It provides a readable repr(): eval(repr(sn)) == sn
  3. It overrides the default comparison. Instead of comparing by id(), it compares attribute values instead.

Hướng dẫn dùng python simplenamespace python

martineau

115k25 gold badges160 silver badges282 bronze badges

answered May 11, 2016 at 11:33

Hướng dẫn dùng python simplenamespace python

9

A class types.SimpleNamespace provides a mechanism to instantiate an object that can hold attributes and nothing else. It is, in effect, an empty class with a fancier __init__() and a helpful __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')

or

from types import SimpleNamespace

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

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

output:

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

This answer may also be helpful.

answered Feb 5, 2021 at 14:12

Not the answer you're looking for? Browse other questions tagged python python-3.x or ask your own question.

Bạn có thể tạo một lớp đơn giản:

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

và nó sẽ hoạt động theo cách giống hệt như argparse Namespacelớp khi nói đến các thuộc tính:

>>> args = Namespace(a=1, b='c')
>>> args.a
1
>>> args.b
'c'

Ngoài ra, chỉ cần nhập lớp ; nó có sẵn từ argparsemô-đun:

from argparse import Namespace

args = Namespace(a=1, b='c')

Đối với Python 3.3, cũng có types.SimpleNamespace, về cơ bản cũng làm điều tương tự:

>>> from types import SimpleNamespace
>>> args = SimpleNamespace(a=1, b='c')
>>> args.a
1
>>> args.b
'c'

Hai loại là khác biệt; SimpleNamespaceđược sử dụng chủ yếu cho sys.implementationthuộc tính và giá trị trả về của time.get_clock_info().

So sánh thêm:

  • Cả hai lớp đều hỗ trợ kiểm tra bình đẳng; đối với hai trường hợp của cùng một lớp, instance_a == instance_blà true nếu chúng có cùng thuộc tính với cùng giá trị.
  • Cả hai lớp đều hữu ích __repr__để hiển thị những thuộc tính mà chúng có.
  • Namespace()đối tượng hỗ trợ kiểm tra ngăn chặn; 'attrname' in instancelà true nếu cá thể không gian tên có tên thuộc tính attrname. SimpleNamespacekhông làm.
  • Namespace()các đối tượng có một ._get_kwargs()phương thức không có tài liệu trả về một danh sách các (name, value)thuộc tính đã được sắp xếp cho trường hợp đó. Bạn có thể nhận được như nhau cho một trong hai lớp bằng cách sử dụng sorted(vars(instance).items()).
  • Mặc dù SimpleNamespace()được triển khai bằng C và Namespace()được triển khai bằng Python, nhưng việc truy cập thuộc tính không nhanh hơn vì cả hai đều sử dụng cùng một __dict__bộ lưu trữ cho các thuộc tính. Kiểm tra tính bình đẳng và tạo ra biểu diễn nhanh hơn một chút đối với các SimpleNamespace()trường hợp.

142 hữu ích 2 bình luận chia sẻ