# 例:类的概念 class 人类: 名字 = '未命名' # 成员变量 def 说话(内容): # 成员函数 print 内容 # 成员变量赋初始值 某人 = 人类() # 定义一个人类对象某人 某人.名字 = "路人甲" 某人.说话 ('大家好') # 路人甲说话 >>> 大家好! # 输出 |
# 例:类定义及使用 class CAnimal: name = 'unname' # 成员变量 def __init__(self,voice='hello'): # 重载构造函数 self.voice = voice # 创建成员变量并赋初始值 def __del__(self): # 重载析构函数 pass # 空操作 def Say(self): print self.voice t = CAnimal() # 定义动物对象t t.Say() # t说话 >> hello # 输出 dog = CAnimal('wow') # 定义动物对象dog dog.Say() # dog说话 >> wow # 输出 |
# 例:类的继承 class CAnimal: def __init__(self,voice='hello'): # voice初始化默认为hello self.voice = voice def Say(self): print self.voice def Run(self): pass # 空操作语句(不做任何操作) class CDog(CAnimal): # 继承类CAnimal def SetVoice(self,voice): # 子类增加函数SetVoice self.voice = voice def Run(self,voice): # 子类重载函数Run print 'Running' bobo = CDog() bobo.SetVoice('My Name is BoBo!') # 设置child.data为hello bobo.Say() bobo.Run() >> My Name is BoBo! >> Running |
欢迎光临 openKylin论坛 (https://forum.openkylin.top/) | Powered by Discuz! X3.3 |