python中class怎么用


当前第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》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...