1

I want to make a method to be called from class or instance.
For example :

class SomeClass:
    a = 10

    def __init__(self, val):
        self.a = val

    def print_a(self):
        print(self.a)

SomeClass(20).print_a()    # 20
SomeClass.print_a()    # Error!

Here I want to make print_a can be called by class either.
If I use classmethod, the result is wrong.

class SomeClass:
    a = 10

    def __init__(self, val):
        self.a = val

    @classmethod
    def print_a(cls):
        print(cls.a)
        
SomeClass(20).print_a()    # 10  (wrong!)
SomeClass.print_a()    # 10

I hope the result is like this:

SomeClass(20).print_a()    # 20
SomeClass.print_a()    # 10

How can I achieve this?

1
  • This question is similar to: Same name for classmethod and instancemethod. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Aug 12, 2024 at 14:17

1 Answer 1

4

classmethod is simply a descriptor object, you can read about how it could be implemented using pure python in the Descriptor HOWTO. Using that implementation as an inspiration:

from types import MethodType
class HybridMethod:
    def __init__(self, f):
        self.f = f

    def __get__(self, obj, cls=None):
        if obj is None:
            return MethodType(self.f, cls)
        else:
            return MethodType(self.f, obj)

class SomeClass:
    a = 10

    def __init__(self, val):
        self.a = val

    @HybridMethod
    def print_a(self):
        print(self.a)

SomeClass(20).print_a()    
SomeClass.print_a()    
Sign up to request clarification or add additional context in comments.

2 Comments

Very thanks! I think I need some time to figure out how this code works.
@Chun-YeLu read the HOWTO from the beginning. Also, more details in the data model documentation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.