473,666 Members | 1,992 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

A better way of making subsclassing of built-in types stick for attributes?

Is there a better way to make the subclassing of built-in types stick?

The goal is to have the the fields of a class behave like strings with
extra methods attached. That is, I want the fact that the fields are
not strings to be invisible to the client programmers. But I always
want the extras to be there for the clients too.

What I'm doing is subclassing str. Of course, whenever you then set
mystr = 'a string' you loose the extra goodies that I have attached in
the subclass. So, to get around this I set up __get__ers and __set__ers
for the fields.

The question is there a more succinct way to have the extended string
behavior stick than using descriptors?

Just to make things concrete here's some abbreviated sample code:

class Person(Table.Ta ble):
def __init__(self, tcs, gender=None, first=None, last=None,
status=None):
self.gender = gender
self.first = first
self.last = last
self.status = status

# Using mix-ins to get the desired behavior
class Gender(Field.In itAlways, Field.SqlVarcha r):
table = ('F', 'M')
fillNext = -1
@classmethod
def fill(cls, rec):
cls.fillNext += 1
return cls.table[cls.fillNext % 2]

#classes First, Last, & Status are analogous but more complicated

# The descriptors are set up at the bottom of the module like so:
Person.first = Field.Descripto r(First)
Person.gender = Field.Descripto r(Gender)
Person.status = Field.Descripto r(Status)

# Moving along to other stripped supporting code

class Descriptor(obje ct):
def __init__(self, cls, name=None):
self.cls = cls
if name == None:
self.name = cls.__name__.lo wer()
else:
self.name = name.lower()

def __set__(self, inst, value):
if inst.__dict__.h as_key(self.nam e):
inst.__dict__[self.name] = self.cls(inst, value, True)
else:
inst.__dict__[self.name] = self.cls(inst, value, False)

class InitAlways(str) :
def __new__(cls, rec, value, reset):
if reset:
return str.__new__(cls , value)
if value == Empty:
return str.__new__(cls , '')
if value == Fill or value == None: #if value in (None, Fill,
''):
return str.__new__(cls , cls.fill(rec) or '')
return str.__new__(cls , value or '')

May 17 '06 #1
4 1168
"te*********@gm ail.com" <te*********@gm ail.com> writes:
Is there a better way to make the subclassing of built-in types
stick?
They stick. Your new classes are available until you get rid of them.
The goal is to have the the fields of a class behave like strings
with extra methods attached. That is, I want the fact that the
fields are not strings to be invisible to the client
programmers. But I always want the extras to be there for the
clients too.

What I'm doing is subclassing str.
Sounds like the right way to do what you're describing. Your subclass
can then be used to instantiate objects that behave like 'str'
objects, except for the different behaviour you define in your class.
Of course, whenever you then set mystr = 'a string'
.... you're instantiating a 'str' object, since that's what the syntax
you use will do.
you loose the extra goodies that I have attached in the
subclass.


Because you haven't created an object of that subclass.
class GroovyStr(str): ... """ Our groovy extended string class """
... pass
... foo = "Larry"
bar = str("Curly")
baz = GroovyStr("Moe" )
print [type(x) for x in foo, bar, baz]

[<type 'str'>, <type 'str'>, <class '__main__.Groov yStr'>]

The syntax used to make the object assigned to 'foo' is just a
shortcut for the syntax used to assign to 'bar'. If you want to
instantiate anything else, you need to use that explicit syntax, such
as for the object assigned to 'baz'.

If you're hoping that "subclass" means "modify the behaviour of the
original class", you're mistaken. It makes a *new* class that has
behaviour *inherited from* the original class.

--
\ "I stayed up all night playing poker with tarot cards. I got a |
`\ full house and four people died." -- Steven Wright |
_o__) |
Ben Finney

May 17 '06 #2
Thanks.

Ben Finney wrote:
"te*********@gm ail.com" <te*********@gm ail.com> writes:
Of course, whenever you then set mystr = 'a string'
... you're instantiating a 'str' object, since that's what the syntax
you use will do.
you loose the extra goodies that I have attached in the
subclass.


Because you haven't created an object of that subclass.


naturally.

The syntax used to make the object assigned to 'foo' is just a
shortcut for the syntax used to assign to 'bar'. If you want to
instantiate anything else, you need to use that explicit syntax, such
as for the object assigned to 'baz'.

If you're hoping that "subclass" means "modify the behaviour of the
original class", you're mistaken. It makes a *new* class that has
behaviour *inherited from* the original class.


Nah. I was hoping that I hadn't muffed the implementation and there was
a more Pythonic way of doing what I wanted.

Sounds like I've gotten things mostly right from the get go. which is
reassuring for a newbie. using __set__ is the correct way to hide the
vectoring to the __new__ assignment... no further shortcuts.

thanks again
t4

May 17 '06 #3
Le Mercredi 17 Mai 2006 06:17, te*********@gma il.com a écrit*:
I want the fact that the fields are
not strings to be invisible to the client programmers.

You should use properties then.

In [12]: class mystr(str) : pass
....:

In [13]: class myrow(object) :
....: getX = lambda s : s._x
....: setX = lambda s, v : setattr(s, '_x', mystr(v))
....: X = property(getX, setX)
....:
....:

In [14]: r=myrow()

In [15]: r.X = 'toto'

In [16]: r.X
Out[16]: 'toto'

In [17]: type(r.X)
Out[17]: <class '__main__.mystr '>
--
_____________

Maric Michaud
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
May 17 '06 #4
Maric Michaud wrote:
Le Mercredi 17 Mai 2006 06:17, te*********@gma il.com a écrit :
I want the fact that the fields are
not strings to be invisible to the client programmers.

You should use properties then.


I started with that idea, using the recipie 20.2 from the cookbook.
However, this caused a fair amount of code bloat... Err the way I
implemented it did at least. I may be missing a way to regularize the
process and make the whole process cleaner too.

The problem was that I needed to set the properties for all of the
object fields with boilerplate code that looks very much the same. Even
if the boilerplate was small, it was still bigger than the one-line
descriptor definitions at the bottom of the module. Shrinking the
descriptor definitions to a one-liner shrunk the code by a fair bit.
There are many classes (100+ when I'm done) and some of them have a
fair number of fields (up to 50) and all of them have to have the
snazzyStr abilities.

Another problem was esthetics; it forces me to place the main class at
the bottom of the module after the definition of the supporting
classes. Putting the descriptors after the bottom of the module left
the important parts at the top where they should be, IMO.

I wanted to use supporting classes for the field definitions because it
allowed me to use mix-ins. This was the biggest win in the design.

Thanks
t4

May 17 '06 #5

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

Similar topics

354
15791
by: Montrose... | last post by:
After working in c# for a year, the only conclusion I can come to is that I wish I knew c. All I need is Linux, the gnu c compiler and I can do anything. Web services are just open sockets hooked up to interfaces. The Gtk is more than enough gui.
2
1279
by: jon.brookins | last post by:
Hello everyone! I'd like to know which method is better for making a copy of an existing database in SQL Server 2000, restoring from a backup of the original, or using DTS to copy the objects to the new database. Any caveats or drawbacks to either method? I'm just trying to lay the groundwork for internal policies for managing our databases, and I just want to make sure we use the best method. Thanks!
85
3255
by: masood.iqbal | last post by:
I know that this topic may inflame the "C language Taleban", but is there any prospect of some of the neat features of C++ getting incorporated in C? No I am not talking out the OO stuff. I am talking about the non-OO stuff, that seems to be handled much more elegantly in C++, as compared to C. For example new & delete, references, consts, declaring variables just before use etc. I am asking this question with a vested interest. I...
2
2080
by: meh | last post by:
I'm not sure if I have the right concept going. I am making a custom TabPage and executing it from a button click event. It works fine I'm just thinking I might be missing the finer points of the c# language. If not maybe I'm starting to catch on. Would like comments...better???...simpler???... Here is the code.... tia meh // Build New Tab Page // string title = "tabPage" + (tabControl1.TabCount + 1).ToString();
26
2007
by: Jeff_Relf | last post by:
Hi Olaf_Baeyens ( and Linonut ), Microsoft C++ is really it's latest version of MS_C, as Microsoft is not supporting the latest C standard, C99. cout and the STL are pure garbage and should not be used, I say. All the same, I use C++ ( MS_C_7 ) as it allows be to declare variables in_between statements. I also use C++'s & a lot as references look cleaner than pointers.
7
5406
by: Wysiwyg | last post by:
Is there any way to add an embedded resource to a project without copying it to the project's directory? I have shared resources and don't want each project using the images, xml files, etc. to need to be updated with the current copy before being built. I also don't want projects being built with the old copy. Thanks! Bill
10
1492
by: Protoman | last post by:
Which is better for general-purpose programming, C or C++? My friend says C++, but I'm not sure. Please enlighten me. Thanks!!!!! PS I believe the folks over at comp.lang.c++ could add something to this.
22
3976
by: petermichaux | last post by:
Hi, I'm curious about server load and download time if I use one big javascript file or break it into several smaller ones. Which is better? (Please think of this as the first time the scripts are downloaded so that browser caching is out of the equation.) Thanks, Peter
39
3211
by: windandwaves | last post by:
Hi Folk I have to store up to eight boolean bits of information about an item in my database. e.g. with restaurant drive-through facility yellow windows
16
1847
by: Breana | last post by:
Man i am getting a tumor over this. Ok this morning i noticed my game page was all messed up. I moved my site to a new server banner less :) it was all ok last night but now hell. So i re did the code and cleaned it up but now it dont work at all. It selects the box art but thats it! I know its sending the itemid because in the url it shows it. item.php?itemid=2 <? $itemid = $_REQUEST;
0
8356
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
8871
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...
0
8781
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8551
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,...
1
6198
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
5664
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();...
0
4369
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2771
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
2
2011
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.