python-3.x 我们如何检查一个类是否覆盖了从`object`继承的特定方法?

aamkag61  于 2023-03-24  发布在  Python
关注(0)|答案(1)|浏览(112)

我正在考虑写一个类装饰器,它将检查从object继承的特定方法是否被重写。

import io

def check_str_method(kls:type) -> type:
    with io.StringIO() as strm:
        if "__str__" in kls.__dict__:
            print("`__str__` is in `__dict__`", file = strm)
        if "__str__" in dir(kls):
            print("`__str__` is in container returned by `dir(kls)`", file = strm)
        str_method = getattr(kls, "__str__")
        if str_method == object.__str__:
            pass
        if str_method == object.__str__:
            pass
        return kls

@check_str_method
class ChildClass1:
    pass

@check_str_method
class ChildClass2:
    def __str__(self):
        return "I HAVE OVERRIDDEN __str__"

obj1 = ChildClass1()
obj2 = ChildClass2()

print("obj1...", str(obj1))
print("obj2...", str(obj2))

正确的Python方法是什么?我们是否检查mro()(方法解析顺序?)
我们在__bases__中搜索吗?

igetnqfo

igetnqfo1#

我的答案是基于Ashwini Chaudhary的评论。
一些代码,如以下可能工作,但我希望有人会张贴一个更好的答案,他们的答案将得到更多的赞成票比我的。

class tools:

    @classmethod 
    def override_str_method(this_class, kls:type) -> type:
        # if someone did not override the `__str__` method... 
        if "__str__" is object.__str__:
            # ... and if the class is iterable...
            if hasattr(kls, "__iter__"):
                # ... then override the string method ...
                # ... definir un método de sarta
                def __str__(self, key:int):
                    """
                        `__str__` provides an information-lossy
                        method which displays a human-readable
                        abridged version of the object for 
                        debugging purposes.  

                        If you want enough information to 
                        re-construct the object, then use
                        `__repr__`
                    """
                    lyst = list()
                    it = iter(self)
                    try:
                        lefty = next(it)
                        lyst.append(lyst) 
                        while True:
                            righty = next(it)
                            lyst.append("...")
                            lyst.append(righty)
                    except StopIteration:
                        stryng = str()
                    return str(lyst) 
                # termination of definition of __str__
                # terminar de definición de __sarta__ 
            # end check to see if class is iterable 
       # end check for if `__str__` is the default value 
    # end method definition

    @classmethod 
    def override_repr_method(this_class, kls:type) -> type:
        # if someone did not override the `__repr__` method... 
        if "__repr__" is object.__repr__:
            # ... and if the class is iterable...
            if hasattr(kls, "__iter__"):
                # ... then override the representation method ...
                # ... definir un método de representación 
                def __repr__(self, key:int):
                    """
                        `__repr__` provides a string containing
                        sufficient information to re-construct the object.   
                    """
                    lyst = list(iter(self))
                    return repr(lyst) 
                # termination of definition of __repr__
                # terminar de definición de __representación__ 
            # end check to see if class is iterable 
       # end check for if `__repr__` is the default value 
    # end method definition

相关问题