Python之类的构造和继承
类的构造:
#!/usr/bin/env python
# -*- coding:utf8 -*-
# @Time : 2017/11/6 9:46
# @Author : hantong
# @File : class.py
#类的一般形式:一般用class关键字创建一个类,后面跟类名称,类名称可以自定义,最后以冒号结尾
# 格式:
# class Classname:
# "类的说明"
# "类的内容"
class ren(object):
#()中的object可以不写,默认继承object
"This is a new class"
name = 'hanson'
sex = 'man'
age = '30'
a = ren()
#此时的类已经定义完毕,可以使用a(可以自定义)来引用类中定义的内容,实例化类
print(type(a))
print(a.name)
print(a.sex)
print(a.age)
a.age = 31
#类中定义的值可以在引用时自定义更改
print(a.age)
执行结果:
<class '__main__.ren'>
hanson
man
30
31
2.类的属性
#!/usr/bin/env python
# -*- coding:utf8 -*-
# @Time : 2017/11/6 10:06
# @Author : hantong
# @File : class2.py
# 类的构造器
class ren():
def __init__(self,name,sex):
#创建实例的时候传入的属性是name和sex
self.name = name
self.sex = sex
def hello(self):
print('hello {0}'.format(self.name))
print('hello {0}'.format(self.sex))
#格式化name和sexde
test = ren('hanson','M')
#实例化__init__时()中的字符与上面的name,sex对应,必须输入才能正常调用,为空会报错,比如:test = ren()
#但是selt参数不需要传入,python会自动实例化
test.hello()
执行结果:
hello hanson
hello M
3.类的继承
#!/usr/bin/env python
# -*- coding:utf8 -*-
# @Time : 2017/11/6 15:32
# @Author : hantong
# @File : class3.py
#类继承
#格式
# class A: 定义类A
# class B: 定义类B
# class C(A,B): C继承类A和B
class parent:
name = 'parent'
sex = 'M'
class child(parent):
age = '30'
def __init__(self):
print('My name is {0}'.format(self.name))
print('My sex is {0}'.format(self.sex))
#此处name和sex参数子类中没有定义,但是父类中定义了,子类可以继承过来
def hello(self):
print('hello world')
def get_name(self):
return(self.name)
def get_sex(self):
return(self.sex)
# print(self.sex)
a = child()
a.hello()
print(a.get_name())
print(a.get_sex())
执行结果:
My name is parent
My sex is M
hello world
parent
M