保持清醒,不断思考。

Mike lucis


  • 首页
  • 归档
  • 分类
  • 标签
  • 关于
  • 联系
  •     

© 2023 Mike lucis

Theme Typography by Makito

Proudly published with Hexo

备案号: 湘ICP备2021005917号-1

友情链接: Lonely's Bolg

ღゝ◡╹)ノ♡

面对对象思想

发布于 2021-04-30 Python  Advance 

¶ 见Python源代码/注释

Code:

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
class Employee:
'所有员工的基类'
empCount = 0

# 定义属性
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1

# 定义方法
def displayCount(self):
print("Total : %d " % Employee.empCount)

def displayEmployee(self):
print("Name : ", self.name, ", Salary: ", self.salary)


# 创建 Employee 类的第一个对象
emp1 = Employee("Zara", 2000)
# 创建 Employee 类的第二个对象
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()

# print("Total Employee %d" % Employee.empCount)
Employee.displayCount(Employee)

Run:

1
2
3
Name :  Zara , Salary:  2000
Name : Manni , Salary: 5000
Total : 2

下面我们深入研究一下类的属性/方法:

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class JustCounter:
__copy = "Mikelucis"
__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._JustCounter__copy) # 可使用 object._classname__attrName 可访问到私有变量
print(counter.__secretCount) # 报错,实例化类不能访问私有变量

Run:

1
2
3
4
5
6
7
8
1
2
2
Mikelucis
Traceback (most recent call last):
File "e:\Programming-Sty\Python\exm_python_adv\类属性与方法.py", line 25, in <module>
print(counter.__secretCount) # 报错,实例化类不能访问私有变量
AttributeError: 'JustCounter' object has no attribute '__secretCount'

分享到 

 上一篇: 类的继承 下一篇: Systemd 基础教程:命令篇 

© 2023 Mike lucis

Theme Typography by Makito

Proudly published with Hexo

备案号: 湘ICP备2021005917号-1

友情链接: Lonely's Bolg

ღゝ◡╹)ノ♡