473,563 Members | 2,653 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1397
On Oct 3, 1:04 pm, Adam Lanier <a...@krusty.ma doff.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.ma doff.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_somethin g(item) for item in some_iterable]
2. where return_somethin g(item) is a "conditiona l assignment":
>>result = a if condition_is_tr ue 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
6311
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 def foo(self, data): self.attr1=data self.attr2.append(data) The initialization of attr1 is obviously OK, all instances of Father redefine it in the...
13
2356
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. Two sub-classes have the relationship to communicate back and forth through this pointer. The pointer is responsible inside Top class for allocating...
15
9042
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 the purpose of learning to work with C++. It therefore makes some sense for me to give the situation the amount of consideration presented below. To...
3
1807
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 abstract parent with four basic functions: Open, Read, Write, and Close. // Note alot of the stuff has been left out // just to give a basic picture...
1
2260
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 ~A() ;
11
2223
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, Struct is may be better...but i am looking for some advise from the experts on this? Assumptions: it is possible for some operations, i may have 8000 to...
6
2109
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 responsible for instantiating the orders class? Would it be the ui layer or the master class in the business layer? thanks,
43
2044
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 within main? (It just doesn't "feel" right to me). Example 1: class MyProg { public:
6
2127
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 times when I program, I will create objects for a specific purpose for a program and if I need to add to it I just add the code.
29
2206
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 "new" contract. I have a method in my contract class called "Save" which is called like this... dim oContract as new Contract
0
7659
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7580
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
1
7634
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7945
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5208
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3618
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2079
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1194
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
916
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.