I have an object that needs to have some 4-5 values passed to it. To illustrate:
class Swoosh():
spam = ''
eggs = ''
swallow = ''
coconut = ''
[... methods ...]
Right now, the way to use Swoosh is:
swoosh = Swoosh()
swoosh.set_spam('Spam!')
swoosh.set_eggs('Eggs!')
swoosh.set_swallow('Swallow!')
swoosh.set_coconut('Migrated.')
I’m having doubts whether this is Pythonic or is this too much Java influence. Or is it just necessary? Also, in case you’re wondering why I’m using setters instead of simply accessing the object variables – some basic validation has to be done there, hence the set_ methods.
I reckon I could provide a different way to initialize a Swoosh – provide an __init__() that would accept a dict/list?
Anyway, I’m just looking for help/advice from someone more experienced with this stuff.
Thanks in advance for any input on this.
Firstly you’re using old style classes. You really, really should be using new style classes that inherit from
object:Defining an
__init__method that takes arguments is definitely the Pythonic way of doing things:This would allow you to do:
Like any other Python function the
__init__method can have default values for arguments, e.g.If you want to validate attributes as they’re set you should use standard
propertyattributes rather than creating your own setters. If you do it this way you can usemyobject.spamin your code like with an ordinary attribute but your setter method is still run.For example:
Note:
propertywill not work unless you’re using new-style classes as described above.In your example you have:
This is often presented as a quick way of setting defaults for attributes for an object. It’s fine but you need to understand what is actually happening. What’s going on is that you’re setting attributes on the class. If an object doesn’t have an attribute Python will look to see if it’s defined on the class and return the value from there (as this is what you want for methods).
If you want to set default values for object attributes you’re much better off setting default values for the arguments in
__init__as described above rather than usingclassattributes.