NO.16类一般形式,构造器,继承

来源:互联网 发布:中海达数据导出 编辑:程序博客网 时间:2024/06/07 21:14
#!/usr/bin/env python# -*- coding:utf-8 -*-# @Time  : 2017/10/25 23:04# @author : hezefan# @file  : 8.1.py'''类的一般形式'''##object是一个超级类,所有的类都在他的基础上进行改写,不写的话默认object类##自定义一个类,包括定义了类的方法class ren(object):    name = 'hezefan'    sex = 'man'    def hello(self):        print('hello world.')a = ren()#调用类print(type(a))print(a.name)print(a.sex)a.hello()##更改类的值a.name = 'fanfan'print(a.name)'''python类的构造器'''class ren1():    def __init__(self,name,sex):        self.name = name        self.sex = sex    age = 28             ##这种写法会把属性写死,视情况而定    def hello(self):        print('hello {0},you sex is {1}'.format(self.name,self.sex))test = ren1('hezefan','man')test.hello()print(test.age)
#!/usr/bin/env python# -*- coding:utf-8 -*-# @Time  : 2017/10/26 15:20# @author : hezefan# @file  : 8.2.py'''类的继承'''#最简单的继承实例,B继承了类A的方法,而且B也可以新增自己的方法,也可以继承两类的方法class A():    passclass B(A):    passclass C(A,B):    pass###1、子类调用父类的时候,方法与变量先从子类中查找,如果没有,再到父类中查找。###2、如果变量名字、方法名字相同,子类的变量会覆盖父类###3、__init__在子类中要重写,初始化的参数不能被别的类调用,需要用super方法来调用class parent():    name ='parent'    sex = 'man'    def __init__(self):        print('hello {0},you are a {1}'.format(self.name,self.sex))    def get_name(self):        print(self.name)    def get_sex(self):        print(self.sex)class child(parent):    name = 'child'    age = 18    def __init__(self):        print('hello {0},you are a {1}'.format(self.name,self.sex))    def get_name(self):        print(self.age)a=child()print('#######'*50)print(a.get_name())

 
原创粉丝点击