Python method-wrapper type?

后端 未结 3 816
被撕碎了的回忆
被撕碎了的回忆 2020-11-30 22:39

What is the method-wrapper type in Python 3? If I define a class like so:

class Foo(object):
    def __init__(self, val):
        self.val = val
    def __e         


        
3条回答
  •  借酒劲吻你
    2020-11-30 23:09

    Below some testcode from my variable inspection routines. Defined class Tst, which has a __str__ method. To find out if an instance of a class has either __repr__ or __str__ defined, you can test for hasattr(obj.__str__, '__code__'):

    Example:

    class Tst(object):
        """ Test base class.
        """
        cl_var = 15
    
        def __init__(self, in_var):
            self.ins_var = in_var
    
        def __str__(self):
            # Construct to build the classname ({self.__class__.__name__}).
            # so it works for subclass too.
            result = f"{self.__class__.__name__}"
            result += f"(cl_var: {self.__class__.cl_var}, ins_var: {self.ins_var})"
            return result
    
        def show(self):
            """ Test method
            """
            print(self.ins_var)
    
    
    t5 = Tst(299)
    
    
    print('\n\n----- repr() ------')
    print(f"obj.repr(): {repr(t5)}")
    print(f"obj.repr.class type: {type(t5.__repr__.__class__)}")
    print(f"obj.repr.class.name: {t5.__repr__.__class__.__name__}")
    print(f"obj.__repr__ has code: {hasattr(t5.__repr__, '__code__')}")
    
    print('\n\n----- str() ------')
    print(f"obj.str(): {str(t5)}")
    print(f"obj.str.class type: {type(t5.__str__.__class__)}")
    print(f"obj.str.class.name: {t5.__str__.__class__.__name__}")
    print(f"obj.__str__ has code: {hasattr(t5.__str__, '__code__')}")
    

    Returns:

    ----- repr() ------
    obj.repr(): <__main__.Tst object at 0x107716198>
    obj.repr.class type: 
    obj.repr.class.name: method-wrapper
    obj.__repr__ has code: False
    
    
    ----- str() ------
    obj.str(): Tst(cl_var: 15, ins_var: 299)
    obj.str.class type: 
    obj.str.class.name: method
    obj.__str__ has code: True
    

    Since __repr__ isn't defined on the class, it defaults to the __repr__ on base-class object via the method-wrapper and gives a default output. __str__ is defined (and thus a method), so the test hasattr(t5.__str__, '__code__') results True.

提交回复
热议问题