0

In Python we can add attributes to an object (class) dynamically, for example:

class Foo(object):
    pass

foo = Foo()
foo.a = 10

My question might be a bit theoretical. So, it's handy. But why should we use that feature??? Is there any particular situation when this approach will be preferable? What about encapsulation?

khelwood
  • 55,782
  • 14
  • 81
  • 108
user35603
  • 765
  • 2
  • 8
  • 24
  • 1 word, metaprogramming. Write code that changes your code at run-time.Imagine that you could write filter_tablename_by_columnname and it automatically generates that function as you call it, grabbing whatever you wrote in place of tablename and columname and using those directly. It's very VERY powerful. – Prodigle Feb 12 '19 at 15:35

1 Answers1

6

In a word: Flexibility. I've used dynamic properties when needing to pass data with GUI objects to a method that handles an event attached to them as one example. I'm sure there are dozens of other uses.

That said, if you're the type of person that likes to have forced attributes and not allow new ones added dynamically you can do so. I can imagine a few places that it's useful, for example helping to ensure you're not setting the wrong value (typo) in your code. Something of a self check.

In order to restrict/prevent the addition of dynamic values you can add a __slots__ property to the class as exampled below.

class Foo(object):
    __slots__ = ['val', 'val2']
    pass

foo = Foo()
foo.val = 10

print(foo.val)

foo.b = 5 # throws exception
print(foo.b) 
Dave
  • 592
  • 3
  • 15