How to extend Class instance

前端 未结 4 1216
礼貌的吻别
礼貌的吻别 2021-01-20 06:50

MyClass is defined in module.py. There is no way we can modify it. But we do know the Class definition looks like this:

class MyCla         


        
4条回答
  •  旧时难觅i
    2021-01-20 07:01

    You could subclass it as well:

    class MyClass:
        def method(self, msg):
            print 'from method:', msg
    
    def function(msg):
        print 'from function:', msg
    
    class MyNewClass(MyClass):
        def method(self, msg):
            function(msg)
            MyClass.method(self, msg)
    

    And use it like:

    >>> a = MyNewClass()
    >>> a.method("test")
    from function: test
    from method: test
    

    Or, if you want to make your class a "new-style" class (for Python 2 - judging by your print statements) - just have MyClass inherit from object and then you can user super:

    class MyClass(object):  # object added here
        def method(self, msg):
            print 'from method:', msg
    
    def function(msg):
        print 'from function:', msg
    
    class MyNewClass(MyClass):
        def method(self, msg):
            function(msg)
            super(self.__class__, self).method(msg)  # super added here
    

提交回复
热议问题