How to tell which subclass was used to instantiate object

Frank Millman frank at chagford.com
Mon May 3 06:01:54 EDT 2004


Peter Otten <__peter__ at web.de> wrote in message news:<c72ch0$6nk$04$1 at news.t-online.com>...
> Frank Millman wrote:
> 
> > I have recently introduced the concept of a 'table type', such as
> > 'Master' or 'Transaction', and have written my own subclasses with
> > standard methods to handle each type of table. The table type is
> > passed as an argument to the 'open' function. which now checks for a
> > user-defined subclass first, if not found checks the type to see if a
> > standard subclass exists, if not found instantiates the main class.
> > This works well.
> > 
> > The concern is that a table may be of type Master, but a user may
> > create their own subclass and inherit from Table instead of Master by
> > mistake. I want to detect this error and raise an exception.
> 
> How about providing a subclass for every table the user might want to
> subclass:
> 
> class Table:
>     def __init__(self, name=None):
>         if name is None:
>             try:
>                 name = self.name
>             except AttributeError:
>                 name = self.__class__.__name__
>         self.name = name
> 
> class Master(Table):
>     pass
> 
> class Transaction(Table):
>     pass
> 
> # provide a suggestively named class for every table in your application
> class Employees(Table): pass
> class Departments(Master): pass
> class Invoices(Transaction):
>     name = "not-a-legal-identifier"
> 
> 
> for cls in [Employees, Departments, Invoices]:
>     print cls().name
> 
> 
> Now the user can just subclass Employees without having to care whether it
> has to be derived from Transaction, Master, Table or whatever. 
> If he needs to know, he can discover it on the command line:
> 
> >>> issubclass(Employees, Transaction)
>  False
> >>> issubclass(Invoices, Transaction)
>  True
> >>>
> 
> An additional benefit is that user code is shielded to some extent from
> modifications in your code, e. g., you could later change the base of
> Employees from Table to Master without requiring changes in client code.
> 
> Peter

Thanks a lot for this, Peter. I will give it some thought. However, as
John has given me an easy answer, I will stick with that for now.

Frank



More information about the Python-list mailing list