from collections import namedtuple FooT = namedtuple('Foo', 'foo bar') def Foo(foo=None, bar=None): return FooT(foo,bar) foo = Foo() foo.foo = 29 throws attribute error
So my use case is a data structure that has optional fields. but should be able to change it if necessary.
A defaultdictshould match what you want. It works by providing it with a build function that it calls every time access to the unset element. Here is a demo:
defaultdict
>>> from collections import defaultdict >>> d = defaultdict(lambda:None) >>> d['foo'] = 10 >>> d['bar'] = 5 >>> print d['baz'] None >>> d['baz'] = 15 >>> print d['baz'] 15
Tuples are, by definition, immutable. Named vertices follow this pattern.
In python3, it appears that you can use SimpleNamespace [1]. If you want to just use the read / write data structure, although you can create a class and set restrictions on its members.
[1] - Python , .. namedtuple
, , . namedtuple, ok ( ) _replace, , .
_replace
from collections import namedtuple FooT = namedtuple('Foo', 'foo bar') def Foo(foo=None, bar=None): return FooT(foo,bar) foo = Foo() foo = foo._replace(foo=29)
, tutorial , None undefined ? :
class Foo(object): def __getattr__(self, name): return None
, defaultdict, , .
?
class Foo(object): def __init__(foo=None, bar=None): self.foo = foo self.bar = bar foo = Foo() foo.foo = 29
Source: https://habr.com/ru/post/1598444/More articles:Try Catch block in destructor - c ++Does the Python range generator generate all values or give them gradually? - pythonggplot2 aes_string () does not like "rownames (mtcars)" when inside the function is rКак использовать Hibernate Spatial в запросах HQL? - javad3.js: Responses to scaling Mousewheel Accordingly - javascriptDifference and advantages of JoinWithTiny, JoinWithHuge and joinHint - apache-flinkIOS template replication: Instagram style tabs - iosSpark job SBT Merge Merge Conflict Merge When Power On Spark Streaming Kinesis ASL library - scalaSpecifying the expanded file name for the AAR artifact in the Android library project - androidКак дублировать строки на основе столбца счетчика - pythonAll Articles