Initializing object variables - a Java approach, a Python approach? -
i have object needs have 4-5 values passed it. illustrate:
class swoosh(): spam = '' eggs = '' swallow = '' coconut = '' [... methods ...]
right now, way 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 pythonic or java influence. or necessary? also, in case you're wondering why i'm using setters instead of accessing object variables - basic validation has done there, hence set_
methods.
i reckon provide different way initialize swoosh
- provide __init__()
accept dict
/list
?
anyway, i'm looking help/advice more experienced stuff.
thanks in advance input on this.
firstly you're using old style classes. really, really should using new style classes inherit object
:
class swoosh(object):
defining __init__
method takes arguments pythonic way of doing things:
def __init__(self,spam,eggs,swallow,coconut): self.spam = spam self.eggs = eggs self.swallow = swallow self.coconut = coconut
this allow do:
s = swoosh('spam!','eggs','swallow','migrated')
like other python function __init__
method can have default values arguments, e.g.
def __init__(self,spam,eggs,swallow,coconut='migrated.'): self.spam = spam self.eggs = eggs self.swallow = swallow self.coconut = coconut
if want validate attributes they're set should use standard property
attributes rather creating own setters. if way can use myobject.spam
in code ordinary attribute setter method still run.
for example:
@property def spam(self): """i'm 'spam' property.""" return self._spam @spam.setter def spam(self, value): if not value.endswith("!"): raise valueerror("spam must end !") # store value in "private" _spam attribute self._spam = value @spam.deleter def spam(self): del self._spam
note: property
not work unless you're using new-style classes described above.
in example have:
class swoosh(): spam = '' eggs = '' swallow = '' coconut = ''
this presented quick way of setting defaults attributes object. it's fine need understand happening. what's going on you're setting attributes on class. if object doesn't have attribute python see if it's defined on class , return value there (as want methods).
if want set default values object attributes you're better off setting default values arguments in __init__
described above rather using class
attributes.
Comments
Post a Comment