当前第2页 返回上一页
# 例:类定义及使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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 # 输出
|
Python编程中类可以承继父类属性,形式为class 类名(父类),子类可以继承父类的所有方法和属性,也可以重载父类的成员函数及属性,须注意的是子类成员函数若重载父类(即名字相同),则会使用子类成员函数
# 例:类的继承
1 2 3 4 5 6 7 8 9 10 11 | 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
|
以上就是python中class怎么用的详细内容,更多文章请关注木庄网络博客!!
返回前面的内容
相关阅读 >>
Python递归求阶乘的方法
Python中的def是什么意思
Python如何安装http server
pycharm找不到解释器怎么办
学Python可以做什么
Python中的基础点
在 flask 中集成 vue
Python爬虫 使用真实浏览器打开网页的两种方法总结
Python递归函数,二分查找算法简介
Python以太坊虚拟机实现py-evm的内容介绍
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » python中class怎么用