我们如何检查一个类是否覆盖了继承自 `object` 的特定方法?

问题描述 投票:0回答:1

我正在考虑编写一个类装饰器来检查从

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))

执行此操作的正确 pythonic 方法是什么?我们是否检查

mro()
(方法解析顺序?)

我们在

__bases__
搜索吗?

python python-3.x decorator python-decorators
1个回答
0
投票

我的回答基于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 
© www.soinside.com 2019 - 2024. All rights reserved.