knowledge

类的初始化

the definition of class

1
2
3
4
5
6
class ClassName:
<statement-1>
.
.
.
<statement-N>

a simple example

1
2
3
4
5
6
7
8
9
# two ways without parameters
class MyClass:
i = 12345
def f(self):
return 'hello world'
#the other way is instantiation
class MyClass:
def __init__(self):
self.data = []

含参的类

1
2
3
4
5
6
7
8
9
10
class High_school_student():

school = "BUPT"

def __init__(self,age,sex):
self.age = age
self.sex = sex
studen1 = High_school_student(18,'M')
print("The age of student is"+str(student1.age))
print(student1.school)

类的私有化

通过在属性成员的名称前加下滑线”__“实现成员的私有化

1
2
3
4
5
6
class High_school_student():
def __init__(self,age,sex)
self.__age = age
self.__aex = sex
student1 = High_school_student(18,'M')
print("The age of student is"+str(student.age))

得到的结果是

image-20221026104659804

但是私有化成员并非不可访问,可以通过_类名__私有变量的方式来进行访问

image-20221026105330360

另外除了属性成员(attribute references),方法(method)也可进行私有化

类的继承(Inheritance)

The syntax for a derived class definition looks like this:

1
2
3
4
5
6
class DeriveClassName(BaseClassName):
<statement-1>
.
.
.
<statement-N>:
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
class people:
# define basic attribute
name = ' '
age = 0
# define private attribute
__weight = 0
# define methods
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))
# inheritance
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,sekf.age,self,grade))

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

image-20221026111905952

Practice

定义一个名为Circle的类,该类表示圆形,它的属性有center和radius,其中center是一个Point对象,而radius是一个数。

实例化一个Circle对象,来表示一个圆心在(150,100),半径为75的圆形。

编写一个函数point_in_circle接收一个Circle对象和一个Point对象,并党Point处于Circle的边界或其界内时,返回True

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
30
import math

class Point():
def __init__(self,x,y):
self.x =x
self.y =y

class Circle():
def __init__(self,x,y,radius):
self.center = Point(x,y)
self.radius = radius
def distance(self,p1,p2):
#距离可以采用两点横纵坐标之差的根号下平方和的形式
dist = math.sqrt((p1-self.center.x)**2+
(p2-self.center.y)**2)
return dist

circle1 = Circle(150,100,75)
point1 = Point(100,100)

def point_in_circle(C1,P1):
#用distance方法求得圆心和点间的距离
dist = C1.distance(P1.x,P1.y)
#如果两点间距离小于半径则返回True
if C1.radius>=dist:
return True
else :
return False
output = point_in_circle(circle1,point1)
print(output)