| 
  • If you are citizen of an European Union member nation, you may not use this service unless you are at least 16 years old.

  • Buried in cloud files? We can help with Spring cleaning!

    Whether you use Dropbox, Drive, G-Suite, OneDrive, Gmail, Slack, Notion, or all of the above, Dokkio will organize your files for you. Try Dokkio (from the makers of PBworks) for free today.

  • Dokkio (from the makers of PBworks) was #2 on Product Hunt! Check out what people are saying by clicking here.

View
 

ClassTricks

Page history last edited by PBworks 14 years, 6 months ago



 

Instances with shared attributes

 

source

 

> > class Stack:

> > list = []

> Okay, this has me a little weirded-out. How is this different from

> def __init__(self):

> self.list = []

 

When you access an attribute of an instance but the instance does not have an attribute with the required name Python looks for the attribute in the class instead. So in the first case it would look as though each instance has a 'list' attribute, but it is the same value shared between all instances. In the second case each instance has its own 'list' attribute.

 

Q: Do I need getters/setters like in java?

 

A: NO! use `__get__` method on properties. Read the docs for the built in `property()` function. It's a nice mechanism to actually avoid all those getters and setters because you can turn "simple" attributes into "computed" attributes without changing the API of the objects.

Comments (0)

You don't have permission to comment on this page.