Python对象

太久没写了~补上补上

类和对象是什么

类是现实世界或思维世界中的实体在计算机中的反映

它将数据以及这些数据上的操作封装在一起

类的定义

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# 面向对象
# 有意义的面向对象
# 类 = 面向对象
# 类,对象
# 类最基本的作用:封装

class Student():
# 一个班级的总数
sum = 0
# 类变量 实例变量
name = 'liupeng' # 特征
age = 0
# 私有变量 __
__score = 0
# 构造函数
# self显胜于隐
def __init__(self,name,age):
# 初始化对象的属性
self.age = age
self.name = name
# 输出的为行参
print(age)
print(name)
# 访问类变量
self.__class__.sum += 1
print('当前班级总人数为:' + str(self.__class__.sum))
# print(Student.sum)

# 行为
# 实例方法
def do_homework(self):
print('name:'+ self.name)
print('age:'+ str(self.age))
print('homework')

# 类方法
# 装饰器
@classmethod
def plus_sum(cls):
cls.sum +=1
print(cls.sum)

# 静态方法
@staticmethod
def add(x,y):
print(Student.sum)
print('This is a static methond')

# 私有方法
def __myGirl():
print('WhyME~')


# 实例化
student1 = Student('石敢当',18)
student2 = Student('喜来乐',19)
print(student1.name)
print(student2.name)
print(Student.name)
student1.do_homework()
# 类方法调用
Student.plus_sum()
student1.plus_sum()
# 静态方法调用
Student.add(1,2)
student1.add(1,2)
# 私有方法直接调用(报错)
student1.__myGirl()
# 私有变量直接调用(报错)
print(student1.__score)
print(student1._Student__score) # 跳过私有 可以直接访问。。。这机制也是没谁了
# 直接调用(添加实例变量)
student1.__score = -1
print(student1.__score)
# 打印类中的实例变量字典
print(student1.__dict__)

类的继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from python5 import Person

class Student(Person):

def __init__(self,school,name,age):
self.school = school
#Person.__init__(self,name,age)
super(Student,self).__init__(name,age)

def do_homework(self):
super(Student,self).do_homework()
print('english homework ~')


# 继承测试
print(Student.sum)
student1 = Student('人民路小学','石敢当',18)
student1.getName()
student1.getAge()
student1.do_homework()
# print(Student.__dict__)
# print(Person.__dict__)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Person():
sum = 0
def __init__(self,name,age):
self.name = name
self.age = age

def getName(self):
print(self.name)

def getAge(self):
print(self.age)

def do_homework(self):
print('parent homework ~')