class Milo():
name='csvt'
def fun1(self):
print self.name
print '我是公有方法'
def __fun2(self):
print self.name
print '我是私有方法'
def classfun(self):
print self.name
print '我是类方法'
def staticfun():
print self.name
print '我是静态方法'
公有方法可以直接调用例如Milo().fun1()
私有方法不能直接调用需要间接调用,例如将fun1函数改为:
def fun1(self):
print self.name
print '我是公有方法'
self.__fun2()
则可以调用Milo().fun1()来调用私有方法 __fun2
这里面有个很有意思的错误:
class text:
... fisrst=123
... second=456
... def f(self):
... print 'self'
...
>>> text.f()
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: unbound method f() must be called with text instance as first argument (got nothing instead)
>>>
解决方法是在def f(self)的上面加上一个@classmethod 则可以直接调用text.f()
或者赋值 classnewf=classmethod(f) 调用text.classnewf()同样可以显示里面的内容
还有一个代码变量命名问题,两个单词以上的变量名首字母大写
#!/usr/bin/python
#coding:utf-8
#author: gavingeng
#date: 2011-12-03 10:50:01
class Person:
def __init__(self):
print "init"
@staticmethod
def sayHello(hello):
if not hello:
hello='hello'
print "i will sya %s" %hello
@classmethod
def introduce(clazz,hello):
clazz.sayHello(hello)
print "from introduce method"
def hello(self,hello):
self.sayHello(hello)
print "from hello method"
def main():
Person.sayHello("haha")
Person.introduce("hello world!")
#Person.hello("self.hello")
#TypeError: unbound method hello() must be called with Person instance as first argument (got str instance instead)
print "*" * 20
p = Person()
p.sayHello("haha")
p.introduce("hello world!")
p.hello("self.hello")
if __name__=='__main__':
main()
可以看出来classmethod和staticmethod的区别:
staticmethod 基本上和一个全局函数差不多,只不过可以通过类或类的实例对象(python里光说对象总是容易产生混淆, 因为什么都是对象,包括类,而实际上类实例对象才是对应静态语言中所谓对象的东西)来调用而已, 不会隐式地传入任何参数。这个和静态语言中的静态方法比较像。
classmethod 是和一个class相关的方法,可以通过类或类实例调用,并将该class对象(不是class的实例对象)隐式地 当作第一个参数传入。就这种方法可能会比较奇怪一点,不过只要你搞清楚了python里class也是个真实地 存在于内存中的对象,而不是静态语言中只存在于编译期间的类型。
正常的方法就是和一个类的实例对象相关的方法,通过类实例对象进行调用,并将该实例对象隐式地作为第一 个参数传入,这个也和其它语言比较像。
上面部分引自http://genggeng.iteye.com/blog/1290458