A
Adam Lanier
Relatively new to python development and I have a general question
regarding good class design.
Say I have a couple of classes:
Class Foo:
params = [ ]
__init__( self, param ):
...
Class Bar:
data = None
__init__( self, data ):
...
The class is going to be a wrapper around a list of Bars() (among other
things). I want the ability to pass to the constructor of Foo either:
a string 'baz'
a Bar object Bar( 'baz' )
a list of strings and/or bars ( 'baz', Bar( 'something else' ))
Am I going to have to use isinstance() to test the parameter to __init__
to see what type of data I'm passing in, i.e.,
Class Foo:
params = [ ]
__init__( self, param ):
if isinstance( param, list ):
for p in param:
addParam( p )
elif isinstance( param, str):
addParam( param )
addParam( self, param ):
if isinstance( param, Bar ):
self.params.add( param )
elif isinstance( param, str ):
self.params.add( Bar( param ))
else:
raise TypeError( "wrong type of input" )
Am I missing something here or is there a more Pythonic way to
accomplish this?
regarding good class design.
Say I have a couple of classes:
Class Foo:
params = [ ]
__init__( self, param ):
...
Class Bar:
data = None
__init__( self, data ):
...
The class is going to be a wrapper around a list of Bars() (among other
things). I want the ability to pass to the constructor of Foo either:
a string 'baz'
a Bar object Bar( 'baz' )
a list of strings and/or bars ( 'baz', Bar( 'something else' ))
Am I going to have to use isinstance() to test the parameter to __init__
to see what type of data I'm passing in, i.e.,
Class Foo:
params = [ ]
__init__( self, param ):
if isinstance( param, list ):
for p in param:
addParam( p )
elif isinstance( param, str):
addParam( param )
addParam( self, param ):
if isinstance( param, Bar ):
self.params.add( param )
elif isinstance( param, str ):
self.params.add( Bar( param ))
else:
raise TypeError( "wrong type of input" )
Am I missing something here or is there a more Pythonic way to
accomplish this?