类 class

定义一个类

使用 class 关键字定义一个类。

1
2
3
4
5
6
7
8
class People:
name=None
age=None
def eat(self):
print("吃东西")

p = People() # 实例化
p.eat()

构造函数

众所周知,js 的构造函数是 constructor,c#的构造函数是与类名同名的不带返回值的方法。
而在 python 中构造函数是__init__()。

1
2
3
4
class People:
def __init__(self,a,b):
self.a=a
self.b=b

注意实例化的时候要给构造函数传参。

self

类的方法与普通的函数只有一个特别的区别——它们必须有一个额外的第一个参数名称, 按照惯例它的名称是 self。
有点类似 js 和 c#的 this。
当你定义一个类,并在类中定义方法时,第一个参数通常被命名为 self,尽管你可以使用其他名称,但强烈建议使用 self,以保持代码的一致性和可读性。

类的继承

基本理论

在定义类的时候使用括号()包住要继承的父类。
继承多个父类使用逗号分隔。
子类的方法和属性可以与父类同名,表示覆写父类的方法或属性。

代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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 说: 我 %d 岁。" %(self.name,self.age))

#单继承示例
class student(people):
grade = ''
def __init__(self,n,a,w,g):
#调用父类的构函
people.__init__(self,n,a,w)
self.grade = g
#覆写父类的方法
def speak(self):
print("%s 说: 我 %d 岁了,我在读 %d 年级"%(self.name,self.age,self.grade))



s = student('ken',10,60,3)
s.speak()

私有属性与方法

基本理论

__private_attrs:两个下划线开头,声明该属性为私有,不能在类的外部被使用或直接访问。在类内部的方法中使用时 self.__private_attrs。
__private_method:两个下划线开头,声明该方法为私有方法,只能在类的内部调用 ,不能在类的外部调用。self.__private_methods。

代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class JustCounter:
__secretCount = 0 # 私有变量
publicCount = 0 # 公开变量

def count(self):
self.__secretCount += 1
self.publicCount += 1
print (self.__secretCount)

counter = JustCounter()
counter.count()
counter.count()
print (counter.publicCount)
print (counter.__secretCount) # 报错,实例不能访问私有变量

运算符重载示例

重载加法运算符。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b

def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)

def __add__(self,other):
return Vector(self.a + other.a, self.b + other.b)

v1 = Vector(2,10)
v2 = Vector(5,-2)
print (v1 + v2)