python类调用自己方法,Python-为什么我可以使用实例调用类方法?

New to Python and having done some reading, I'm making some methods in my custom class class methods rather than instance methods.

So I tested my code but I hadn't changed some of the method calls to call the method in the class rather than the instance, but they still worked:

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()

This produces:

class method foo called with __main__.myClass.

class method foo called with __main__.myClass.

instance method bar called with <__main__.myclass instance at>.

So what I'm wondering is why I can call a class method (foo) on an instance (thing.foo), (although it's the class that gets passed to the method)? It kind of makes sense, as 'thing' is a 'myClass', but I was expecting Python to give an error saying something along the lines of 'foo is a class method and can't be called on an instance'.

Is this just an expected consequence of inheritance with the 'thing' object inheriting the foo method from its superclass?

If I try to call the instance method via the class:

myClass.bar()

then I get:

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

which makes perfect sense.

解决方案

You can call it on an instance because @classmethod is a decorator (it takes a function as an argument and returns a new function).

Here is some relavent information from the 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.

There's also quite a good SO discussion on @classmethod here.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值