Adding method to class at run-time: bad style?

Grant Edwards invalid at invalid
Tue Apr 7 10:37:35 EDT 2009


I realize that technically all methods are added to classes at
"run-time", but what I'm talking about is this:

   import ClientForm

   def controlEqual(self,other):
       return (self.type == other.type) and \
              (self.name == other.name) and \
              (self.value == other.value) and \
              (self.disabled == other.disabled) and\
              (self.readonly == self.readonly)
   
   def controlNotEqual(self,other):
       return not (self==other)
   
   ClientForm.Control.__eq__ = controlEqual
   ClientForm.Control.__ne__ = controlNotEqual
   
   def formEqual(self,other):
       if len(self.controls) != len(other.controls):
           return False
       for (c1,c2) in zip(self.controls,other.controls):
           if c1 != c2:
               return False
       return True
   
   def formNotEqual(self,other):
       return not (self==other)
   
   ClientForm.HTMLForm.__eq__ = formEqual
   ClientForm.HTMLForm.__ne__ = formNotEqual

It works fine, but it seems like it might be dangerous (or just
bad form) to insert methods into existing classes like that.
Perhaps it would be safer to make sure that __eq__, __ne__,
and __cmp__ don't exist before adding my own?

-- 
Grant Edwards                   grante             Yow! NEWARK has been
                                  at               REZONED!!  DES MOINES has
                               visi.com            been REZONED!!



More information about the Python-list mailing list