作者:chen_h
微信号 & QQ:862251340
微信公众号:coderpai
一、类定义
class<类名>:
语句
类实例化之后,可以使用其属性,实际上,创建一个类之后,可以通过类名访问其属性。如果直接使用类名修改其属性,那么将直接影响到已经实例化的对象。
类的私有属性:
__private_attrs 两个下划线开头,声明该属性为私有,不能在类地外部被使用或直接访问,在类内部的方法中使用时 self.__private_attrs
类的方法:
在类地内部,使用 def 关键字可以为类定义一个方法,与一般函数定义不同,类方法必须包含参数 self,且为第一个参数。
私有的类方法:
__private_method 两个下划线开头,声明该方法为私有方法,不能在类地外部调用。在类的内部调用 self.__private_methods
类的专有方法:
__init__ 构造函数,在生成对象时调用
__del__ 析构函数,释放对象时使用
__repr__ 打印,转换
__setitem__按照索引赋值
__getitem__按照索引获取值
__len__获得长度
__cmp__比较运算
__call__函数调用
__add__加运算
__sub__减运算
__mul__乘运算
__div__除运算
__mod__求余运算
__pow__称方
举个例子
#类定义
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("{0} is speaking: I am {1} years old, {2} weight".format(self.name, self.age, self.__weight))
p = people('tom',10,30)
p.speak()
p.__dict__
p.weight = 100
p.speak()
p.__dict__
### output
tom is speaking: I am 10 years old, 30 weights
{'_people__weight': 30, 'age': 10, 'name': 'tom'}
tom is speaking: I am 10 years old, 30 weights
{'_people__weight': 30, 'age': 10, 'name': 'tom', 'weight': 100}
二、继承类定义
2.1 单继承
class<类名>(父类名)
<语句>
eg:
class childbook(book)
age = 10
举个例子:
#单继承示例
class student(people):
grade = ''
def __init__(self, name, age, weight, grade):
people.__init__(self, name, age, weight)
self.grade = grade
#覆写父类的方法
def speak(self):
print("{0} is speaking: I am {1} years old, and I am in grade {2}".format(self.name, self.age, self.grade))
s = student('ken', 10, 20, 3)
s.speak()
### output
ken is speaking: I am 10 years old, and I am in grade 3
2.2 类的多重继承
class<类名>(父类1,父类2,父类3,...,父类n)
<语句1>
需要注意的是圆括号中父类的顺序,若是父类中有相同的方法名,而在子类使用时未指定,那么 python 从左至右进行搜索。即方法在子类中未找到时,从左到右查找父类中是否包含方法。
举个例子:
#另一个类,多重继承之前的准备
class speaker():
topic = ''
name = ''
def __init__(self, name, topic):
self.name = name
self.topic = topic
def speak(self):
print("I am {0},I am a speaker!My topic is {1}. FROM SPEAKER".format(self.name,self.topic))
#多重继承
class sample(speaker,student):
a =''
def __init__(self,name, age, weight, grade, topic):
student.__init__(self, name, age, weight, grade)
speaker.__init__(self, name, topic)
test = sample("Tim",25,80,4,"Python")
test.speak() #方法名同,默认调用的是在括号中排前地父类的方法
### output
I am Tim,I am a speaker!My topic is Python. FROM SPEAKER
三、下划线变量的含义
核心风格:避免用下划线作为变量名的开始。
“单下划线” 开始的成员变量叫做保护变量,意思是只有类对象和子类对象自己能访问到这些变量;如果修改,无需通知外部。
“双下划线” 开始的是私有成员,意思是只有类对象自己能访问,连子类对象也不能访问到这个数据。
以单下划线开头(_foo)的代表不能直接访问的类属性,需通过类提供的接口进行访问,不能用 “from xxx import *” 而导入;除非在init.py中使用all显示定义。
以双下划线开头的(__foo)代表类的私有成员;编译时会翻译成:_classname__foo, 且不会被子类覆盖。
以双下划线开头和结尾的(foo)代表python里特殊方法专用的标识,如 init()代表类的构造函数。