2011-10-29 65 views

回答

10

你可以定義一個Default混入:

class Default(object): 
    def __repr__(self): 
     return '-'.join(
      str(getattr(self,key)) for key in self.__dict__ if not key.startswith('_')) 
    def __eq__(self,other): 
     try: 
      return all(getattr(self,key)==getattr(other,key) 
         for key in self.__dict__ if not key.startswith('_')) 
     except AttributeError: 
      return False 


class Foo(Default): 
    def __init__(self): 
     self.bar=1 
     self.baz='hi' 

foo=Foo() 
print(foo) 
# hi-1 

foo2=Foo() 
print(foo==foo2) 
# True 

foo2.bar=100 
print(foo==foo2) 
# False