Re: Referring to the class name from a class variable where inheritance is involved

2011-12-06 Thread Matt Saxton

On 06/12/11 15:57, Paul Moore wrote:

I want to set up an inheritance hierarchy. The base class will define
a string value which should include the class name, but I don't want
people who inherit from my class to have to remember to override the
value.

If I do this using an instance variable, it's reasonably easy:


class Base:

... def __init__(self):
... self.key = 'Key_for_' + self.__class__.__name__
... def display(self):
... print self.key
...

class Inherited(Base):

... pass
...

b = Base()
i = Inherited()
b.display()

Key_for_Base

i.display()

Key_for_Inherited

Rather than having the key for every instance, I'd like to use a class
variable, but I can't see how I'd make that work (a class variable
which is inherited but has a different value in derived classes). I
could use a classmethod,but that feels like even more overkill than an
instance attribute.

Is there a way of doing this via class variables or something, or more
relevantly, I guess, what would be the idiomatic way of doing
something like this?

Thanks,
Paul


You can use a metaclass for this:

>>> class BaseMeta(type):
... def __new__(mcs, name, bases, dict):
... dict['key'] = 'Key_for_%s' % name
... return type.__new__(mcs, name, bases, dict)
...
>>> class Base:
... __metaclass__ = BaseMeta
...
>>> class Inherited(Base):
... pass
...
>>> Base.key
'Key_for_Base'
>>> Inherited.key
'Key_for_Inheritor'

You can find more info on metaclasses here:
http://http://docs.python.org/reference/datamodel.html#customizing-class-creation


Regards
Matt
--
http://mail.python.org/mailman/listinfo/python-list


Re: message box in Tkinter

2010-08-17 Thread Matt Saxton
On Tue, 17 Aug 2010 04:02:23 -0700 (PDT)
Jah_Alarm  wrote:

> 
> When I try importing messagebox from Tkinter i get an error message
> that this module doesn't exist.
> 

I believe what you want is Tkinter.Message


-- 
Matt Saxton 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reversing a List

2010-09-01 Thread Matt Saxton
On Wed, 1 Sep 2010 09:00:03 -0400
Victor Subervi  wrote:

> Hi;
> I have this code:
> 
>   cursor.execute('describe products;')
>   cols = [item[0] for item in cursor]
>   cols = cols.reverse()
>   cols.append('Delete')
>   cols = cols.reverse()
> 
> Unfortunately, the list doesn't reverse. If I print cols after the first
> reverse(), it prints None. Please advise.

The reverse() method modifies the list in place, but returns None, so just use
>>> cols.reverse()

rather than
>>> cols = cols.reverse()

> Also, is there a way to append to
> the front of the list directly?
> TIA,
> beno

The insert() method can do this, i.e.
>>> cols.insert(0, 'Delete')

-- 
Matt Saxton 
-- 
http://mail.python.org/mailman/listinfo/python-list