2

I do Java programming and recently started learning Python via the official documentation. I see that we can dynamically add data attributes to an instance object unlike in Java:

class House:
  pass

my_house = House()
my_house.number = 40
my_house.rooms = 8
my_house.garden = 1

My question is, in what situations is this feature used? What are the advantages and disadvantages compared to the way it is done in Java?

2 Answers 2

2

It can also be used when dynamically creating classes; see for instance this tutorial:

http://onlamp.com/pub/a/python/2003/04/17/metaclasses.html?page=1

or this one on Mix-ins, a programming technique that uses this capability to provide better encapsulation and modularity to object oriented code:

http://www.linuxjournal.com/article/4540

The first tutorial uses setattr(classname, "propertyname", value) instead of the classname.property = value syntax, but they are the same.

Sign up to request clarification or add additional context in comments.

3 Comments

There are so many better ways of fulfilling the needs of the asker in that thread...
Yes; it was my intention to post a factual answer quickly and edit with a more useful one. The tutorial is better, but I'm still looking for a clear practical example of the exact syntax he's asking about.
personal experience in using that sort of syntax would do fine as well.
1

It's not often done from outside of the class unless the object is being used as a bucket of sorts. It's done an awful lot inside __init__() of course, to provide values to attributes that will be used elsewhere.

Oh, and speaking of Java...

1 Comment

That was a very useful video and a bit funny too!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.