python 面向对象

面向对象学习:代码

 1 #!/usr/bin/python
 2 # -*- coding: UTF-8 -*-
 3 class Employee:
 4     empCount=0
 5     __secret_Phone=0   ##私有成员变量,不能在外部类的外部访问
 6     public_Phone=0   ##公有成员变量
 7     
 8     def __init__(self,name,salary):##四个下划线,类似构造函数
 9         self.name=name
10         self.salary=salary
11         Employee.empCount+=1
12         print("secret phone:%d"%Employee.__secret_Phone)##访问私有成员变量        
13     def display(self):
14         print("Total employee: %d" % Employee.empCount)##%前面没有,与C不同
15     def inFunc(self):
16         print(self)##地址
17         print(self.__class__)##类名
18 
19     def diplayEmployee(self):
20         print("Name:",self.name,",Salary:",self.salary)
21     def EmployeeMethod(self):
22         print("Employee method!")
23     def __add__(self,other):##运算符重载,双下划线为特殊方法
24         return Employee(self.name+other.name,self.salary+other.salary)
25 
26     def __del__(self):##析构函数
27         class_name=self.__class__.__name__
28         print(class_name,"销毁")
29 
30 
31 emp1=Employee("wj",1000)##实例化
32 emp2=Employee("lj",1000)##实例化
33 emp1.inFunc()##调用内部函数
34 emp3=emp1+emp2 ##重载运算符
35 print("emp3 __add__:",emp3.diplayEmployee())
36 print("public phone:%d"%emp1.public_Phone)
37 emp1.diplayEmployee()##调用成员函数
38 emp1.display()
39 emp1.age=8 ##添加新成员
40 emp1.age=9 ##修改新成员
41 print(emp1.age)
42 del emp1.age ##删除成员
43 print("hasattr:",hasattr(emp1,'age'))##检查是否存在age
44 print("getattr",getattr(emp1,'name'))##返回name值
45 print("setattr",setattr(emp1,'name',"lj"))##设置name为"lj"
46 ##内置函数
47 print("Employee.__doc__:",Employee.__name__)
48 
49 del emp1    ##删除类的实例
50 
51 class Manager(Employee):##继承,多个类(A,B)
52     workers=30
53     def __init__(self):
54         Manager.workers=10
55     def display(self):
56         print("Total workers:%d" % Manager.workers)
57     def ManagerMethod(self):
58         print("Manager method!")
59 
60 M1=Manager()#
61 M1.EmployeeMethod()##调用子类方法
62 M1.display()##调用父类方法重写方法
63 M1.workers=40##访问成员变量

执行结果:

===================== RESTART: D:\python3.7\20180425.py =====================
secret phone:0
secret phone:0
<__main__.Employee object at 0x000002114D915A58>
<class '__main__.Employee'>
secret phone:0
Name: wjlj ,Salary: 2000
emp3 __add__: None
public phone:0
Name: wj ,Salary: 1000
Total employee: 3
9
hasattr: False
getattr wj
setattr None
Employee.__doc__: Employee
Employee 销毁
Employee method!
Total workers:10

 

posted @ 2018-04-25 23:11  日积硅步,以致千里  阅读(138)  评论(0编辑  收藏  举报