In Python one can use setattr
to add a new attribute to an object like the following code
class Foobar:
def __init__(self):
pass
foobar = Foobar()
setattr(foobar, 'foo', 123)
print(foobar.foo)
output
123
I know in Julia there is setfield!
but it doesn't allow to add a new field like setattr
in Python.
so my question is there is a way to add a new field to an object of a composite type?
is there is way to add a new field to an object of a composite type?
No. Julia is intentionally designed without this kind of local dynamic behavior. If you need to dynamically add and remove fields then you're really using the object as a dictionary with different syntax. In Julia, you would use an actual dictionary – Dict
or other associative collection – for that kind of usage. This has no worse performance than an object in a language like Python, although it will have worse performance than a statically defined type in Julia, but that is the inherent cost of objects with dynamic fields – which is precisely why objects don't work that way in Julia.
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加