私有属性&&方法的定义&访问限制

 1 '''
 2 在Python中,可以为实例属性和⽅法设置私有权限,即设置某个实例属性或实例⽅法不继承给⼦类
 3 
 4 设置私有权限的⽅法:在属性名和⽅法名 前⾯ 加上两个下划线 __。
 5 '''
 6 
 7 class Master(object):
 8     def __init__(self):
 9         self.kongfu = '[古法煎饼果子配方]'
10 
11     def make_cake(self):
12         print(f'运用{self.kongfu}制作煎饼果子')
13 
14 
15 class School(object):
16     def __init__(self):
17         self.kongfu = '[黑马煎饼果子配方]'
18 
19     def make_cake(self):
20         print(f'运用{self.kongfu}制作煎饼果子')
21 
22 
23 class Prentice(School, Master):
24     def __init__(self):
25         self.kongfu = '[独创煎饼果子技术]'
26         # self.money = 2000000
27         # 定义私有属性
28         self.__money = 2000000
29 
30     # 定义私有方法
31     def __info_print(self):
32         print('这是私有方法')
33 
34     def make_cake(self):
35         self.__init__()
36         print(f'运用{self.kongfu}制作煎饼果子')
37 
38     def make_master_cake(self):
39         Master.__init__(self)
40         Master.make_cake(self)
41 
42     def make_school_cake(self):
43         School.__init__(self)
44         School.make_cake(self)
45 
46 
47 class Tusun(Prentice):
48     pass
49 
50 
51 tu_sun = Tusun()
52 
53 # print(tu_sun.money)  #  无法访问  AttributeError: 'Tusun' object has no attribute 'money'
54 # print(tu_sun.__money)  #  无法访问 AttributeError: 'Tusun' object has no attribute '__money'
55 
56 tu_sun.__info_print()  # 报错:AttributeError: 'Tusun' object has no attribute '__info_print'

 注意:私有属性和私有⽅法只能在类⾥⾯访问和修改。

posted @ 2023-07-19 23:58  Allen_Hao  阅读(29)  评论(0)    收藏  举报