What I want to do seems weird, in short, I am trying to build a new class and copy instance/static/class methods from another class without doing inheritance (i.e., I only want a class with only a few methods). As I looked it up on the web, it seems people were suggesting what I did in illustration (New Class), but as I tried to test it, the class method declared in the new class seems to still point to the previous class (Old Class).
This is what I did:
class OldClass(object):
current_count = 1
def __init__(self):
pass
@classmethod
def method_class(cls):
cls.current_count += 1
def method_normal(self):
return 2
# new class
class NewClass(object):
method_class_copy = OldClass.method_class
method_normal_copy = OldClass.method_normal
Checking __self__ gives the following:
class_self = getattr(NewClass.method_class_copy, '__self__', None)
print(class_self)
it returns:
<class '__main__.OldClass'>
but checking the instance method after being instantiated:
instance_self = getattr(NewClass().method_normal_copy, '__self__', None)
print(instance_self)
as you can see, it still refers to the OldClass, and if I run the class method NewClass.method_class_copy(), the OldClass.current_count will increase its value the way I defined.
it returns:
<__main__.NewClass object at 0x000001D8CC1AEA88>
- How do I construct a (new) class with the class method's __self__ actually refers to the NewClass rather than the OldClass?
- why instance method is "automatically adjusted"?
Thanks