473,372 Members | 799 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,372 software developers and data experts.

Class design question

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?

Oct 3 '07 #1
4 1390
On Oct 3, 1:04 pm, Adam Lanier <a...@krusty.madoff.comwrote:
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?
I would use variable argument list for this; it's also consistent with
your example Foo( 'baz', Bar( 'something else' )), otherwise you need
to call it as Foo([ 'baz', Bar( 'something else' ) ])

# always inherit from object unless you have a good reason not to
class Foo(object):

# XXX this is a class instance, shared by all Foo instances;
# XXX probably not what you intended
params = [ ]

def __init__(self, *args):
# uncomment the following line for instance-specific params
# self.params = []
for arg in args:
if not isinstance(arg, Bar):
# let the Bar constructor to do typechecking or whatnot
arg = Bar(arg)
self.params.add(arg)
HTH,
George

Oct 3 '07 #2
On Oct 3, 2:27 pm, George Sakkis <george.sak...@gmail.comwrote:
On Oct 3, 1:04 pm, Adam Lanier <a...@krusty.madoff.comwrote:
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?

I would use variable argument list for this; it's also consistent with
your example Foo( 'baz', Bar( 'something else' )), otherwise you need
to call it as Foo([ 'baz', Bar( 'something else' ) ])

# always inherit from object unless you have a good reason not to
class Foo(object):

# XXX this is a class instance, shared by all Foo instances;
# XXX probably not what you intended
params = [ ]

def __init__(self, *args):
# uncomment the following line for instance-specific params
# self.params = []
for arg in args:
if not isinstance(arg, Bar):
# let the Bar constructor to do typechecking or whatnot
arg = Bar(arg)
self.params.add(arg)

HTH,
George
Or even better (Python 2.5):

class Foo(object):
def __init__(self, *args):
self.params = [arg if isinstance(arg, Bar) else Bar(arg) for
arg in args]

George

Oct 3 '07 #3
On Wed, 2007-10-03 at 18:47 +0000, George Sakkis wrote:

I would use variable argument list for this; it's also consistent
with
your example Foo( 'baz', Bar( 'something else' )), otherwise you
need
to call it as Foo([ 'baz', Bar( 'something else' ) ])
Good point, this is what was tripping me up...

# always inherit from object unless you have a good reason not to
class Foo(object):

# XXX this is a class instance, shared by all Foo instances;
# XXX probably not what you intended
params = [ ]

def __init__(self, *args):
# uncomment the following line for instance-specific params
# self.params = []
for arg in args:
if not isinstance(arg, Bar):
# let the Bar constructor to do typechecking or
whatnot

This is also tangentially what I was asking, Should type-checking be
done in the caller or the callee (so to speak). I guess good OOP
practice would be to push it down the call stack.
arg = Bar(arg)
self.params.add(arg)

Or even better (Python 2.5):

class Foo(object):
def __init__(self, *args):
self.params = [arg if isinstance(arg, Bar) else Bar(arg) for
arg in args]
Interesting, I'm not familiar with this idiom...
Oct 3 '07 #4
Adam Lanier wrote:
>class Foo(object):
def __init__(self, *args):
self.params = [arg if isinstance(arg, Bar) else Bar(arg) for
arg in args]

Interesting, I'm not familiar with this idiom...

These are two idioms actually:

1. a "list comprehension":
>>newlist = [return_something(item) for item in some_iterable]
2. where return_something(item) is a "conditional assignment":
>>result = a if condition_is_true else b
/W
Oct 3 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

50
by: Dan Perl | last post by:
There is something with initializing mutable class attributes that I am struggling with. I'll use an example to explain: class Father: attr1=None # this is OK attr2= # this is wrong...
13
by: Bryan Parkoff | last post by:
I have created three classes according to my own design. First class is called CMain. It is the Top Class. Second class and third class are called CMemory and CMPU. They are the sub-classes....
15
by: Steven T. Hatton | last post by:
The following may strike many of you as just plain silly, but it represents the kind of delelima I find myself in when trying to make a design decision. This really is a toy project written for...
3
by: fernandez.dan | last post by:
I'm still learning how to use Object Oriented concepts. I'm have a basic question dealing with design. I have two classes that deal with I/O pertaining to network and usb that inherit from an...
1
by: Alfonso Morra | last post by:
if I have a class template declared as ff: (BTW is this a partial specialization? - I think it is) template <typename T1, myenum_1 e1=OK, my_enum_2=NONE> class A { public: A(); virtual...
11
by: dimension | last post by:
If my intentions are to create objects that encapsulates data rows in a table, is it better to use a Struct or Class? Based on what i read, if my objects will simply have get and set methods,...
6
by: rodchar | last post by:
Hey all, I'm trying to understand Master/Detail concepts in VB.NET. If I do a data adapter fill for both customer and orders from Northwind where should that dataset live? What client is...
43
by: Tony | last post by:
I'm working with GUI messaging and note that MFC encapsulates the message loop inside of a C++ class member function. Is this somehow inherently less robust than calling the message loop functions...
6
by: JoeC | last post by:
I have a question about designing objects and programming. What is the best way to design objects? Create objects debug them and later if you need some new features just use inhereitance. Often...
29
by: Brad Pears | last post by:
Here is a simple OO design question... I have a Contract class. The user can either save an existing contract or they start off fresh with a blank contract, fill in the data and then save a...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.