Python绑定方法,未绑定方法,类方法,实例方法,静态方法

时间:2023-03-08 21:49:18
Python绑定方法,未绑定方法,类方法,实例方法,静态方法

>>> class foo():
clssvar=[1,2]
def __init__(self):
self.instance=[1,2,3]
def hehe(self):
print 'haha' >>> foo.hehe
<unbound method foo.hehe>
>>> a=foo()
>>> a.hehe
<bound method foo.hehe of <__main__.foo instance at 0x01D60468>>

>>> foo.hehe()


Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
foo.hehe()
TypeError: unbound method hehe() must be called with foo instance as first argument (got nothing instead)


非绑定方法必须被实例调用

class foo():
foovar=1
def __init__(self):
self.avar=3
def method(self):
methodvar=2
print 'hello',methodvar
class foo1(foo):
foo1var=4
def __init__(self,nm):
foo.__init__(self)
#调用非绑定方法——父类构造器
self.fooo=self.avar
print self.fooo
def method(self):
pass
a=foo1(2)
#1.这是我根据Python核心编程上的例子写的,我们要弄清楚一点:类里面的方法就是非绑定方法,实例里面的方法就是绑定的。
#2.既然上面说非绑定方法只能被实例调用,那么我们是如何调用一个类的非绑定方法的呢?实际上用类不能调用非绑定方法,无非是没有给
self参数,那么我们给它就是。

>>> foo.hehe(a)
haha

#self=a
同样的道理,调用父类构造器给子类用,那么直接给self(就是子类对象)就可以啦!
# 我们一般都是通过实例来调用,但也可以使用类来调用,比如上面通过调用父类的构造器可以避免子类调用时需要大量参数传递的情况
#coding=utf-8
class A(object):
count=1
def foo(self,x):
#类实例方法
print "executing foo(%s,%s)"%(self,x)
def foo2(self):
self.foo(5)
foo2var=self.count
@classmethod
def class_foo(cls):
#类方法
cls.count=cls.count+1 @staticmethod
def static_foo(x):
#静态方法
x+=1.1
print "executing static_foo(%s)"%x,id(x)
a=A()
b=A()
a.class_foo()
print a.count,b.count,A.count
b.class_foo()
print a.count,b.count,A.count
A.class_foo()
print a.count,b.count,A.count
打印结果
2 2 2
3 3 3
4 4 4 #可以看看我前一篇博文。一个类数据属性,只有通过类来调用时才会改变,通过实例来改变实际上不会对类产生影响。但是如果通过类方法来改,那么即便是实例调用也能改变类数据属性,这我觉得是很危险的。
#一般其它编程语言都会不允许实例调用类方法,比如Java,这样做的好处就是你能很轻松的利用类方法修改类属性。但Python允许实例调用类方法,但请不要这么做!

静态方法

#coding=utf-8
class A(object):
count=1
def foo(self,x):
#类实例方法
print "executing foo(%s,%s)"%(self,x)
def foo2(self):
self.foo(5)
foo2var=self.count
@classmethod
def class_foo(cls):
#类方法
cls.count=cls.count+1 @staticmethod
def static_foo(self,x):
#静态方法
x+=1.1
self.count=3
print "executing static_foo(%s)"%x,id(x)
a=A()
b=A()
a.static_foo(a,2)
print a.count,b.count,A.count
b.static_foo(b,3)
print a.count,b.count,A.count
A.static_foo(A,4)
print a.count,b.count,A.count
输出结果
executing static_foo(3.1) 20196512
3 1 1
executing static_foo(4.1) 20196512
3 3 1
executing static_foo(5.1) 20196512
3 3 3 #一般静态方法不要求你写self,但你可以这么干,同类数据属性的性质一样,类的静态方法修改会影响实例,实例却只影响自身
#id(x)告诉我们静态方法里的变量同样是静态的。