【问题标题】:Default method implementations in python(__str__,__eq__,__repr__,ect.)python中的默认方法实现(__str__,__eq__,__repr__,ect.)
【发布时间】:2011-10-29 09:18:49
【问题描述】:

有什么方法可以将__str__,__eq__,__repr__ 的简单实现添加到类中?

基本上我希望__eq__ 只是所有非前缀实例变量是否相等。
还有一个 __str__/__repr__,它只是命名每个变量并在每个变量上调用 str/repr。
标准库中有这样的机制吗?

【问题讨论】:

    标签: python oop metaprogramming


    【解决方案1】:

    你可以定义一个Default mixin:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-20
      • 2021-09-11
      • 1970-01-01
      • 2017-12-23
      • 2020-01-13
      • 2018-11-23
      • 2013-12-13
      相关资源
      最近更新 更多