Date: 2014-07-7 Title: python 实例方法,静态方法,类方法 Tags: Python Category: It
字面意思:实例的方法,即只有实例能使用的方法,相对于类方法和静态方法。
如:
class Foo: ##init()是生成实例时默认调用的实例方法,用于初始化详细见[__init__方法](#) ###第一个参数默认为self def __init__(self, name): self.name = name self.author="Tulpar" ##又一个实例方法 def hi(self): print self.name print "Created by %s"%self.author
###第一个参数默认为guoshu,作用和self一样 def __init__(guoshu, name): guoshu.name = name guoshu.author="Tulpar" ##又一个实例方法 def hi(guoshu): print guoshu.name print "Created by %s"%guoshu.author
静态方法是一种普通函数,就位于类定义的命名空间中,它不会对任何实例类型进行操作。使用装饰器@staticmethod定义静态方法。类对象和实例都可以调用静态方法
class Foo: ##静态方法走起 @staticmethod def add(a, b): print a + b
运行结果
###生成实例f1 >f1=Foo(u'果树') ###实例能用静态方法 >f1.add(3,5) ###类对象也能使用静态方法 >Foo(3,5) ###输出结果 8 8
正在更新!!
There was an error while loading. Please reload this page.