473,394 Members | 2,063 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,394 software developers and data experts.

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.Table):
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.InitAlways, Field.SqlVarchar):
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.Descriptor(First)
Person.gender = Field.Descriptor(Gender)
Person.status = Field.Descriptor(Status)

# Moving along to other stripped supporting code

class Descriptor(object):
def __init__(self, cls, name=None):
self.cls = cls
if name == None:
self.name = cls.__name__.lower()
else:
self.name = name.lower()

def __set__(self, inst, value):
if inst.__dict__.has_key(self.name):
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 1159
"te*********@gmail.com" <te*********@gmail.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__.GroovyStr'>]

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*********@gmail.com" <te*********@gmail.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*********@gmail.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*********@gmail.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
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...
2
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...
85
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...
2
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...
26
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...
7
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...
10
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...
22
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...
39
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
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...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
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,...
0
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...
0
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,...
0
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...
0
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...
0
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...

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.