python-3.x - 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 且对用户不友好。
解决方案
如果方法的行为不同,您可以简单地在初始化时更改该名称公开的方法:
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
推荐阅读
- python - 如何提高谷歌云功能的速度?
- azure - Can connect to one Azure DB but not another
- c - Arrays, pointers, and memory management toy example question in C
- javascript - Why isn't the innerHTML changing? Its supposed to count up when clicked
- python - Incorrect element returned from list
- php - logic in meta_query wordpress query
- python - Python 3.6.8: infinite looping forked thread causes no stderr logging on systemd due to default buffering
- c++ - 从中删除项目时如何有效地迭代 std::(unordered)set?
- python - 使用 win10toast 时出错:pywintypes.error: (-2147467259, 'Shell_NotifyIcon', 'Unspecified error')
- java - org.postgresql.util.PSQLException:BigDecimal 类型的值错误:使用 JPA 的 {1}