Python - 为什么我可以用实例调用类方法?

标签 python python-2.7 inheritance class-method

Python 新手并阅读了一些资料后,我在我的自定义类类方法而不是实例方法中创建了一些方法。

所以我测试了我的代码,但我没有更改一些方法调用以调用类中的方法而不是实例中的方法,但它们仍然有效:

class myClass:
   @classmethod:
   def foo(cls):
      print 'Class method foo called with %s.'%(cls)

   def bar(self):
      print 'Instance method bar called with %s.'%(self)

myClass.foo()
thing = myClass()
thing.foo()
thing.bar()

这会产生:

class method foo called with __main__.myClass.
class method foo called with __main__.myClass.
instance method bar called with <__main__.myClass instance at 0x389ba4>.

所以我想知道的是为什么我可以在实例 (thing.foo) 上调用类方法 (foo),(尽管它是传递给方法的类)?这是有道理的,因为“thing”是一个“myClass”,但我期望 Python 会给出一个错误,说一些类似“foo 是类方法,不能在实例上调用”的内容。

这是否只是“thing”对象从其父类(super class)继承 foo 方法的继承的预期结果?

如果我尝试通过类调用实例方法:

myClass.bar()

然后我得到:

TypeError: unbound method bar() must be called with myClass instance...

这很有道理。

最佳答案

您可以在实例上调用它,因为@classmethod 是一个decorator (它接受一个函数作为参数并返回一个新函数)。

这里是一些来自 Python documentation 的相关信息

It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.

@classmethod here 上也有很好的 SO 讨论.

关于Python - 为什么我可以用实例调用类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30190061/

相关文章:

python - 为什么这不能作为数组成员资格测试?

python - Python 3 中从外部父类的嵌套类继承的嵌套类

python - 使用 tweepy 获取独特的推文

python - 需要基本的 Python 编程帮助 : Arrays and random locations

python - 在Python中将字典列表划分为子字典

python-2.7 - 合并两列 pandas 数据框

c# - 新关键字 : why is the derived method not called?

python - 如何深度复制具有包装函数的对象?

python - 在没有 Django 其余部分的情况下使用 Django 的模板引擎

python - 勾选 Python 中的 Python 实例