本文主要介绍了Python类定义和类继承及类的私有属性、类的方法
1.类的定义
类实例化后,可以使用其属性,实际上,创建一个类之后,可以通过类名访问其属性
如果直接使用类名修改其属性,那么将直接影响到已经实例化的对象
类的方法
在类地内部,使用def关键字可以为类定义一个方法,与一般函数定义不同,类方法必须包含参数self,且为第一个参数
实例如下:
-
#!/usr/bin/env python
-
# -*- coding:utf-8 -*-
-
# Author :Alvin.xie
-
# @Time :2017-11-06 17:17
-
# @file :class2.py
-
-
-
#类定义
-
class people:
-
name = ''
-
age = 0
-
_weight = 0
-
def __init__(self,n,a,w):
-
self.name = n
-
self.age =a
-
self._weight =w
-
def speak(self):
-
print ("%s is speaking: I am %d years old" %(self.name,self.age))
-
-
-
p = people('tom',10,30)
-
p.speak()
运行结果:
tom is speaking: I am 10 years old
2.类的继承
2.1 单继承
-
class <类名>(父类名)
-
<语句>
-
-
eg.
-
class childbook(book)
-
age = 10
2.2 多重继承
-
class 类名(父类1,父类2,....,父类n)
-
<语句1>
需要注意圆括号中父类的顺序,若是父类中有相同的方法名,而在子类使用时未指定,python从左至右搜索,即方法在子类中未找到时,从左到右查找父类中是否包含方法
实例如下:
-
#!/usr/bin/env python
-
# -*- coding:utf-8 -*-
-
# Author :Alvin.Xie
-
# @Time :2017/11/6 22:41
-
# @File :class1.py
-
-
-
# 类定义
-
class People:
-
name = ''
-
age = 0
-
_weight = 0
-
_grade = 0
-
-
def __init__(self, n, a, w, g):
-
self.name = n
-
self.age = a
-
self._weight = w
-
self._grade = g
-
-
def speak(self):
-
print ("%s is speaking: I am %d years old" % (self.name, self.age))
-
-
-
p = People('tom', 10, 30, 1)
-
p.speak()
-
-
-
class Speaker():
-
topic = ''
-
name = ''
-
-
def __init__(self, n, t):
-
self.name = n
-
self.topic = t
-
-
def speak(self):
-
print ("I am %s,I am a speaker!My topic is %s" % (self.name, self.topic))
-
-
-
test = Speaker('Tim', 'Python')
-
test.speak()
-
-
-
# 多重继承
-
class Sample(Speaker, People):
-
a = ''
-
# _grade = 4
-
-
def __init__(self, n, a, w, g, t):
-
People.__init__(self, n, a, w, g)
-
Speaker.__init__(self, n, t)
-
print ("I am %s,I am %d years old,and I am %d, I am in grade %d and my topic is %s" % (self.name, self.age, self._weight, self._grade, self.topic))
-
-
-
test = Sample('Ken', 25, 80, 4, 'python')
执行结果:
tom is speaking: I am 10 years old
I am Tim,I am a speaker!My topic is Python
I am Ken,I am 25 years old,and I am 80, I am in grade 4 and my topic is python
阅读(1040) | 评论(0) | 转发(0) |