如何定义类
class ClassName(base_class[es]):
"optional documentation string"
static_member_declarations
method_declarations
使用 class 关键字定义类。 可以提供一个可选的父类或者说基类; 如果没有合适的基类,
那就使用 object 作为基类。class 行之后是可选的文档字符串, 静态成员定义, 及方法定
义。
class FooClass(object):
'''my very first class:FooClass'''
version = 0.1 #static
def __init__(self,name='hejian'):
'''constructor'''
self.name = name #class instance(data) attribute
print 'Created a class instance for',name
def showname(self):
'''display instance attribute and class name'''
print 'Your name is ',self.name
print 'My name is',self.__class__.__name__ #Class Name
@classmethod
def showver(self):
'''display class(static) attribute'''
print self.version
def addMe2Me(self,x):
return x + x
def getVersion(self):
return self.version
def setVersion(self,ver):
self.version = ver
def getClassName(self):
return self.__class__.__name__
@staticmethod
def staticMethod():
print "static method"
python和java不同的地方
java类属性可以通过类名和实例修改类变量,
python只能通过类名来修改类属性。
foo = FooClass()
foo.setVersion(0.3)
foo.showver()
foo2 = FooClass()
foo2.showver()
输出
Created a class instance for hejian
0.1
Created a class instance for hejian
0.1
foo = FooClass()
foo.setVersion(0.3)
foo.showver()
FooClass.version = 0.3
foo2 = FooClass()
foo2.showver()
输出:
Created a class instance for hejian
0.1
Created a class instance for hejian
0.3