How to tell which subclass was used to instantiate object
Frank Millman
frank at chagford.com
Sat May 1 08:47:20 EDT 2004
Hi all
I have a question regarding inheritance. I have come up with a
solution, but it is not very elegant - I am sure there is a more
pythonic approach. Assume the following class definitions.
class Table:
def __init__(self,table_name,table_type):
class Master(Table):
def __init__(self,table_name,table_type):
Table.__init__(self,table_name,table_type)
class Transaction(Table):
def __init__(self,table_name,table_type):
Table.__init__(self,table_name,table_type)
class Armaster(Master):
def __init__(self,table_name,table_type):
Master.__init__(self,table_name,table_type)
Table is the main class, which represents a database table. Master is
a subclass that encapsulates various common characteristics of a
'master file' type of table. Transaction is a subclass that
encapsulates various common characteristics of a 'transaction file'
type of table. ArMaster is a subclass that is created to handle
specific requirements for the ArMaster table, which is a 'master file'
type of table.
Both of the following would be errors -
class Armaster(Table):
def __init__(self,table_name,table_type):
Table.__init__(self,table_name,table_type)
class Armaster(Transaction):
def __init__(self,table_name,table_type):
Transaction.__init__(self,table_name,table_type)
By inheriting from the incorrect class, the special methods to handle
a 'Master' type table have been bypassed. My question is, how can
Table check that objects have inherited from the correct subclasses?
Here is my inelegant solution. Assume that table_type contains the
string 'Master'.
class Master(Table):
def __init__(self,table_name,table_type):
self.my_type = 'Master'
Table.__init__(self,table_name,table_type)
class Table:
def __init__(self,table_name,table_type):
if hasattr(self,'my_type'):
ok = (self.my_type == table_type)
else:
ok = False
if not ok:
raise RuntimeError('%s must be of type %s' %
(table_name,table_type))
Is there a more direct way for a top-level class to determine which
subclasses were used to instantiate it?
Thanks
Frank Millman
More information about the Python-list
mailing list