面对对象思想
发布于 2021-04-30 Python Advance
Code:
123456789101112131415161718192021222324252627
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:
123
Name : Zara , Salary: 2000Name : Manni , Salary: 5000Total : 2
下面我们深入研究一下类的属性/方法:
1234567891011121314151617
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) # 报错,实例化类不能访问私有变量
12345678
122MikelucisTraceback (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 基础教程:命令篇