473,890 Members | 1,197 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

general class functions

syd
In my project, I've got dozens of similar classes with hundreds of
description variables in each. In my illustrative example below, I
have a Library class that contains a list of Nation classes. In one
case, I might want a Library class with only Nations of with the
continent variable "Europe", and so I'll do something like
library.getCont inent('Europe') which will return a Library() instance
with only European nations. Similarly, I could also want a Library()
instance with only 'small' size nations.

My question follows: is there a way I can make a general function for
getting a subclass with my specific criteria? For instance, can I
pass in an equivalence test or something like that? I have hundreds
of variables like "nation", "continent" , and so forth, and do want to
write a separate "get______" function for each.

This stumped everyone I work with. Help would be greatly
appreciated!!

#!/usr/bin/python
class Library:
def __init__(self,l ist=None):
self.list=list
def add(self,nation ):
try: self.list.appen d(nation)
except: self.list=[nation]
def defineNation(se lf,name,contine nt,size):
nation=Library. Nation()
nation.name=nam e
nation.continen t=continent
nation.size=siz e
self.add(nation )
def getContinent(se lf,continent):
library=Library ()
for nation in self.list:
if nation.isContin ent(continent)= =True:
library.add(nat ion)
return library
def getSize(self,si ze):
library=Library ()
for nation in self.list:
if nation.isSize(s ize)==True:
library.add(nat ion)
return library
def getNameList(sel f):
outList=[]
for nation in self.list:
outList.append( nation.name)
return outList
class Nation:
def __init__(self,n ame=None,contin ent=None,size=N one):
self.name=name # eg, Spain
self.continent= continent # eg, Europe
self.size=size # eg, medium
def isContinent(sel f,continent):
if self.continent= =continent: return True
else: return False def isSize(self,siz e):
if self.size==size : return True
else: return False

library=Library ()
library.defineN ation('Spain',' Europe','medium ')
library.defineN ation('USA','No rthAmerica','la rge')
library.defineN ation('Luxembou rg','Europe','s mall')
library.defineN ation('Portugal ','Europe','med ium')

print library.getName List()
print library.getCont inent('Europe') .getNameList()
print library.getCont inent('Europe') .getSize('small ').getNameList( )
Jul 18 '05 #1
20 1981
syd wrote:
In my project, I've got dozens of similar classes with hundreds of
description variables in each. In my illustrative example below, I
have a Library class that contains a list of Nation classes. In one
case, I might want a Library class with only Nations of with the
continent variable "Europe", and so I'll do something like
library.getCont inent('Europe') which will return a Library() instance
with only European nations. Similarly, I could also want a Library()
instance with only 'small' size nations.

My question follows: is there a way I can make a general function for
getting a subclass with my specific criteria? For instance, can I
pass in an equivalence test or something like that? I have hundreds
of variables like "nation", "continent" , and so forth, and do want to
write a separate "get______" function for each.
You can use getattr to read the Nation attributes by name. Add this
method to Library:
def getMatches(self ,attribute, value):
library=Library ()
for nation in self.list:
if getattr(nation, attribute) == value:
library.add(nat ion)
return library

Now you can call
print library.getMatc hes('continent' , 'Europe').getNa meList()
print library.getMatc hes('continent' , 'Europe').getMa tches('size',
'small').getNam eList()

Is that what you want?
Kent

This stumped everyone I work with. Help would be greatly
appreciated!!

#!/usr/bin/python
class Library:
def __init__(self,l ist=None):
self.list=list
def add(self,nation ):
try: self.list.appen d(nation)
except: self.list=[nation]
def defineNation(se lf,name,contine nt,size):
nation=Library. Nation()
nation.name=nam e
nation.continen t=continent
nation.size=siz e
self.add(nation )
def getContinent(se lf,continent):
library=Library ()
for nation in self.list:
if nation.isContin ent(continent)= =True:
library.add(nat ion)
return library
def getSize(self,si ze):
library=Library ()
for nation in self.list:
if nation.isSize(s ize)==True:
library.add(nat ion)
return library
def getNameList(sel f):
outList=[]
for nation in self.list:
outList.append( nation.name)
return outList
class Nation:
def __init__(self,n ame=None,contin ent=None,size=N one):
self.name=name # eg, Spain
self.continent= continent # eg, Europe
self.size=size # eg, medium
def isContinent(sel f,continent):
if self.continent= =continent: return True
else: return False def isSize(self,siz e):
if self.size==size : return True
else: return False

library=Library ()
library.defineN ation('Spain',' Europe','medium ')
library.defineN ation('USA','No rthAmerica','la rge')
library.defineN ation('Luxembou rg','Europe','s mall')
library.defineN ation('Portugal ','Europe','med ium')

print library.getName List()
print library.getCont inent('Europe') .getNameList()
print library.getCont inent('Europe') .getSize('small ').getNameList( )

Jul 18 '05 #2
On 1 Nov 2004 17:09:53 -0800, sy*********@gma il.com (syd) wrote:
My question follows: is there a way I can make a general function for
getting a subclass with my specific criteria? For instance, can I
pass in an equivalence test or something like that? I have hundreds
of variables like "nation", "continent" , and so forth, and do want to
write a separate "get______" function for each.


Adding the following method to Library

def __getattr__(sel f,name):
if name.startswith ("get_"):
attrname = name[4:]
def filter(value):
library=Library ()
for nation in self.list:
if getattr(nation, attrname) == value:
library.add(nat ion)
return library
return filter
else:
return self.__dict__[name]

you will be able to write

L.get_continent ('Europe').get_ size('small')

because for anything starting with "get_..." will be
generated on the fly a filtering function that looks
for exact match of an attribute. No need for
getContinent, getSize, isContinent and isSize.

HTH
Andrea
Jul 18 '05 #3

"syd" <sy*********@gm ail.com> wrote in message
news:a7******** *************** ***@posting.goo gle.com...
Many many thanks, Andrea and Kent!

To keep changes to calls in my current code to a minimum, I'm hoping I
can encode Andrea's "on-the-fly" get function. I added Andrea's
__getattr__ to my Library() class, populated the class with a few
nations, and tried:
library.get_con tinent('Europe' )

This line creates and returns an instance of Library. I assume that you
imported foo in a python session and then you executed that line. That
results in a call to Library.__repr_ _( ), which is not defined. First of
all, I recommend you change class Library to subclass from object. That's
just good practice in general and in this case it will give you a default
__repr__( ) method. But that's probably not what you want. What you
probably want is to still use a line like:
print library.getCont inent('Europe') .getNameList()
Otherwise, library.get_con tinent('Europe' ) is going to print something like:
<__main__.Libra ry object at 0x00A9F430>

Dan
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "foo.py", line 16, in __getattr__
return self.__dict__[name]
KeyError: '__repr__'

I then commented out lines 15 and 16...
#else:
#return self.__dict__[name]

... and re-ran.
library.get_con tinent('Europe' )

Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'NoneType' object is not callable

I tweaked a bit, but I could not get to the bottom of this problem. I
see the logic here (and it's brilliant I should add, Andrea), but I'm
not sure what is wrong.

Ideas?

Jul 18 '05 #4
Kent Johnson a écrit :
syd wrote:
In my project, I've got dozens of similar classes with hundreds of
description variables in each. In my illustrative example below, I
have a Library class that contains a list of Nation classes. In one
case, I might want a Library class with only Nations of with the
continent variable "Europe", and so I'll do something like
library.getCont inent('Europe') which will return a Library() instance
with only European nations. Similarly, I could also want a Library()
instance with only 'small' size nations.

My question follows: is there a way I can make a general function for
getting a subclass with my specific criteria? For instance, can I
pass in an equivalence test or something like that? I have hundreds
of variables like "nation", "continent" , and so forth, and do want to
write a separate "get______" function for each.

You can use getattr to read the Nation attributes by name. Add this
method to Library:
def getMatches(self ,attribute, value):
library=Library ()
for nation in self.list:
if getattr(nation, attribute) == value:
library.add(nat ion)
return library

Now you can call
print library.getMatc hes('continent' , 'Europe').getNa meList()
print library.getMatc hes('continent' , 'Europe').getMa tches('size',
'small').getNam eList()


<just for the fun...>

You could make it even more simple - and avoid creating useless
instances of Library and Nation - with keyword arguments:

class Library:
[...]
def getAll(self, **kwargs):
library=Library ()
for nation in self.list:
keep = True
for attribute, value in kwargs.items():
if not getattr(nation, attribute) == value:
keep = false
break
if keep :
library.add(nat ion)
return library

print library.getAll( continent='Euro pe').getNameLis t()
print library.getAll( continent='Euro pe', size='small').g etNameList()

This is and 'and' search, you could also have an 'or' search method:

def getAny(self, **kwargs):
library=Library ()
for nation in self.list:
for attribute, value in kwargs.items():
if getattr(nation, attribute) == value:
library.add(nat ion)
break
return library

print library.getAny( continent='Euro pe', size='small').g etNameList()

and then a more generic search:
def getMatches(self , op, **kwargs):
fun = {'or': self.getAny, 'and' : self.getAll}.ge t(op)
return fun(**kwargs):

print library.getMatc hes('and',
continent='Euro pe',
size='small').g etNameList()

print library.getMatc hes('or',
continent='Euro pe',
size='small').g etNameList()

</just for the fun...>

Bruno
Jul 18 '05 #5
bruno modulix <onurb <at> xiludom.gro> writes:

class Library:
[...]
def getAll(self, **kwargs):
library=Library ()
for nation in self.list:
keep = True
for attribute, value in kwargs.items():
if not getattr(nation, attribute) == value:
keep = false
break
if keep :
library.add(nat ion)
return library


I haven't been watching this thread, but I saw a pattern here that Python allows
a much easier solution to. The code:

keep = True
for item in lst:
if test(item):
keep = False
break
if keep:
...

can generally be rewritten as:

for item in lst:
if test(item):
break
else:

For example:
def loop1(lst, test): .... keep = True
.... for item in lst:
.... if test(item):
.... keep = False
.... break
.... if keep:
.... print "reached if"
.... def loop2(lst, test): .... for item in lst:
.... if test(item):
.... break
.... else:
.... print "reached if"
.... loop1(range(10) , lambda x: x == 5)
loop1(range(10) , lambda x: x == 11) reached if loop2(range(10) , lambda x: x == 5)
loop2(range(10) , lambda x: x == 11)

reached if

Always good to take advantage of a language construct when you can. =)

Steve

Jul 18 '05 #6
On Tue, 02 Nov 2004 13:31:42 -0500, Kent Johnson <ke******@yahoo .com>
wrote:
Instead of
return self.__dict__[name]
you need
raise AttributeError, name

self.__dict_ _ has already been tried before __getattr__ is called, you
don't need to try it again.


I hope one day I'll understand python lookup :-)

....

Would it be worse or better to make Library a new-style
class, using __getattribute_ _ instead of __getattr__ and
defaulting to object.__getatt ribute__(self,n ame) in the
"else" part ?

Andrea
Jul 18 '05 #7
syd
> Instead of
return self.__dict__[name]
you need
raise AttributeError, name


Booyah, Kent! This works. For posterity, I'll dump a working code:

#!/usr/bin/python
class Library(object) :
def __init__(self,l ist=None):
self.list=list
def __getattr__(sel f,name):
if name.startswith ("get_"):
attrname = name[4:]
def filter(value):
library=Library ()
for nation in self.list:
if getattr(nation, attrname) == value:
library.add(nat ion)
return library
return filter
else:
raise AttributeError, name
def add(self,nation ):
try: self.list.appen d(nation)
except: self.list=[nation]
def defineNation(se lf,name,contine nt,size):
nation=Library. Nation()
nation.name=nam e
nation.continen t=continent
nation.size=siz e
self.add(nation )
def getNameList(sel f):
outList=[]
for nation in self.list:
outList.append( nation.name)
return outList
class Nation(object):
def __init__(self,n ame=None,contin ent=None,size=N one):
self.name=name # eg, Spain
self.continent= continent # eg, Europe
self.size=size # eg, medium

library=Library ()
library.defineN ation('Spain',' Europe','medium ')
library.defineN ation('USA','No rthAmerica','la rge')
library.defineN ation('Luxembou rg','Europe','s mall')
library.defineN ation('Portugal ','Europe','med ium')

print library.getName List()
print library.get_con tinent('Europe' ).getNameList()
Jul 18 '05 #8
syd
"Dan Perl" <da*****@rogers .com> wrote in message
> library.get_con tinent('Europe' )

This line creates and returns an instance of Library. I assume that you
imported foo in a python session and then you executed that line. That
results in a call to Library.__repr_ _( ), which is not defined. First of
all, I recommend you change class Library to subclass from object. That's
just good practice in general and in this case it will give you a default
__repr__( ) method. But that's probably not what you want. What you
probably want is to still use a line like:
print library.getCont inent('Europe') .getNameList()
Otherwise, library.get_con tinent('Europe' ) is going to print something like:
<__main__.Libra ry object at 0x00A9F430>


You're 100% right, Dan -- I meant to have the "getNameLis t()" tacked
on.

But more importantly, why is subclassing object a good practice in
general? I see under dir(object) that you get some good default
methods. I looked under the documentation, but could not find a good
specific examples as to why this was a good practice. Can you
elaborate, please?
Jul 18 '05 #9
syd
Andrea Griffini <ag****@tin.i t> wrote in message
Would it be worse or better to make Library a new-style
class, using __getattribute_ _ instead of __getattr__ and
defaulting to object.__getatt ribute__(self,n ame) in the
"else" part ?


Can you elaborate here, please? I'm not sure I understand what you mean.
Jul 18 '05 #10

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

Similar topics

3
2438
by: syd | last post by:
Hello all, In my project, I have container classes holding lists of item classes. For example, a container class myLibrary might hold a list of item classes myNation and associated variables like myNation.name='USA' and myNation.continent='North America'. Bottom line, I was hoping to use this structure to marshal the classes to xml.
1
1492
by: Andrew MacLean | last post by:
Hello all, I am fairly new to .NET, but not to VB. I have a couple of questions. 1. Shared Code Base I have a solution with several different applications within it. Many of the applications perform similar functions, such as checking data values for nulls, or building formatted strings. I have created a module (General Functions.vb) to contain these. However, when I add the module as an existing file to my project, .NET's IDE...
1
3274
by: Sean W. Quinn | last post by:
Hey folks, I have a question regarding file handling, and the preservation of class structure. I have a class (and I will post snippets of code later in the post) with both primitive data structures (ints), and more complex data structures (strings and vectors) in it, and would like to write the entire class to a data file that could then be read back and loaded. However I'm having difficulty with this -- I found out (due to an...
39
2832
by: Antoon Pardon | last post by:
I was wondering how people would feel if the cmp function and the __cmp__ method would be a bit more generalised. The problem now is that the cmp protocol has no way to indicate two objects are incomparable, they are not equal but neither is one less or greater than the other. So I thought that either cmp could return None in this case or throw a specific exception. People writing a __cmp__ method could do the same.
7
2250
by: Felix Kater | last post by:
Hi, when I need to execute a general clean-up procedure (inside of a function) just before the function returns -- how do I do that when there are several returns spread over the whole function? My first approach: Use "while(1)" and "break", however this doesn't work if there is another loop inside (since I can't break two loops at the same time):
1
1811
by: jason | last post by:
Hello everyone, I have some general questions about the DataTable object, and how it works. Moderately new to C#, I have plenty of texts describing the language, but not so much to reference ADO.NET objects (only the MSDN help files). I have written a C# Class Library that is responsible for encapsulating database information. All the objects work just fine for singleton record insert, update, select, and delete operations. But now we...
2
1531
by: Kristoffer | last post by:
Hi! I have a general db class (a normal class, that contains the functions and subs to enable me to connect to my database) ok... but, HOW?? Do, I make use of this class in my asp.net application... I need to contact it from my codebehind page... but, I contact my codebehind page with the src= tag, so it compiles when I contact the webpage, and not before...
1
1361
by: Adam Knight | last post by:
Hi all, I am still teething on ASP.NET after flogging ASP for a number of years. What approach is recommend for storing commly used functions ? In classic asp, normally these unrelated helper functions were in a 'include file'. I have thought of writing a class, but in this instance the functions i am refering to are not related and seem to be
6
1917
by: S. Lorétan | last post by:
Hi guys. I am preparing the rewriting of an huge existing application in VB6. This software is a mess of 10 years of patchs and new functionalities added randomly, and didn't have any logical or oriented-object background. This software is used by many differents persons, and there is a LOT of functionalities that exists only for one or two of them. So, I want to use a plugin-based system. That's it for the background.
0
9978
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9821
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11229
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10923
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
10462
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9630
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8016
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7169
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4676
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

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.