和C++类的思想很是相似,直接贴code。
示例代码:
#ex_class_baseuse.py
self_file = __file__
print "\n======void class========="
class CTom: #define class
pass #void code block
tom = CTom() #create instance
print tom #<__main__.CTom instance at 0x0000000002D13D48>
print type(tom) #<type 'instance'>
print type(CTom) #<type 'classobj'>
print dir(tom) #['__doc__', '__module__']
print tom.__doc__ #None
print tom.__module__ #__main__
print "\n======normal class==========="
class CKitty: #define class
_name = "Kitty" #define class attr
_age = 16
def hello(self): #define class method
print "Hello, I am %s, my age is %d" % (self._name, int(self._age))
def update(self, age):
self._age = age
kitty = CKitty()
print kitty #<__main__.CKitty instance at 0x0000000002DD4C88>
print dir(kitty) #['__doc__', '__module__', '_age', '_name', 'hello', 'update']
kitty.hello() #Hello, I am Kitty, my age is 16
kitty.update(18)
kitty.hello() #Hello, I am Kitty, my age is 18
kitty._age = 20
kitty.hello() #Hello, I am Kitty, my age is 20
print kitty.__doc__ #None
print kitty.__module__ #__main__
print kitty.hello #<bound method CKitty.hello of <__main__.CKitty instance at 0x0000000002D442C8>>
print kitty.update #<bound method CKitty.update of <__main__.CKitty instance at 0x0000000002C84388>>
print "\n======class with redef __init__ method======"
class CCar:
_color = "" #car color
_age = 0 #car age
def __init__(self, color, age): #定义构造器
self._color = color
self._age = age
print "create car, color:%s age:%d)" % (self._color, int(self._age))
def update(self, color, age):#define class method
self._color = color
self._age = age
def dump(self):#define class method
print "car, color:%s, age:%d" % (self._color, int(self._age))
car = CCar("red", 1)
print dir(car) #['__doc__', '__init__', '__module__', '_age', '_color', 'dump', 'update']
car.dump() #car, color:red, age:1
car.update("blue",2)
car.dump() #car, color:blue, age:2
print "\n exit %s" % self_file
编译执行:
(end)