A class method which behaves differently when called as an instance method?

后端 未结 5 1355
忘了有多久
忘了有多久 2021-02-01 17:17

I\'m wondering if it\'s possible to make a method which behaves differently when called as a class method than when called as an instance method.

For example, as a skill

5条回答
  •  情书的邮戳
    2021-02-01 17:48

    You can reassign your identity method in init with short lambda function:

    class Matrix(object):
        def __init__(self):
            self.identity = lambda s=self:s.__class__.identity(s)
    
            #...whatever initialization code you have...
            self.size = 10        
    
        @classmethod
        def identity(self, other):
            #...always do you matrix calculations on 'other', not 'self'...
            return other.size
    
    
    m = Matrix()
    print m.identity()
    print Matrix.identity(m)
    

    If you're not familiar with lambda, it creates an anonymous function. It's rarely necessary, but it can make your code more concise. The lambda line above could be rewritten:

        def identity(self):
            self.__class__.indentity(self)
        self.identity = identity
    

提交回复
热议问题