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

后端 未结 5 1260
忘了有多久
忘了有多久 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:40

    @Unknown What's the difference between your's and this:

    class Foo(object):
    
        def _bar(self, baz):
            print "_bar, baz:", baz
    
        def __init__(self, bar):
            self.bar = self._bar
            self.baz = bar
    
        @classmethod
        def bar(cls, baz):
            print "bar, baz:", baz
    
    In [1]: import foo
    
    In [2]: f = foo.Foo(42)
    
    In [3]: f.bar(1)
    _bar, baz: 1
    
    In [4]: foo.Foo.bar(1)
    bar, baz: 1
    
    In [5]: f.__class__.bar(1)
    bar, baz: 1
    

提交回复
热议问题