首页 > 解决方案 > Python 类方法也是实例方法

问题描述

我有一个类,原则上在其类主体中包含有关它的所有信息。实例化时,它会接收与类属性一起形成常规实例的附加信息。我现在的问题在于我需要实现一个方法,当从类对象调用它时应该将其调用为类方法,但从实例调用时应该将其调用为常规实例方法:

例如类似的东西


class MyClass(object):
    attribs = 1, 2, 3

    def myMethod(self, args):
        if isclass(self):
            "do class stuff"
        else:
            "do instance stuff"


MyClass.myMethod(2) #should now be called as a class method, e.g. I would normally do @classmethod

MyClass().myMethod(2) #should now be called as instance method

当然,我可以将它声明为 staticmethod 并显式传递实例或类对象,但这似乎相当不合 Python 且对用户不友好。

标签: python-3.xclass-methodinstance-methods

解决方案


如果方法的行为不同,您可以简单地在初始化时更改该名称公开的方法:

class MyCrazyClass:
    @classmethod
    def magicmeth(cls):
        print("I'm a class")

    def _magicmeth(self):
        print("I'm an instance")

    def __init__(self):
        self.magicmeth = self._magicmeth

推荐阅读