【再回首Python之美】【类】基本使用

和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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值