私有变量
除了在对象内部(包括其子类)不能访问的“私有”实例变量在Python中不存在。但是,大多数Python代码遵循一个约定:以下划线(例如_spam)为前缀的名称应被视为API的非公开部分(无论它是函数,方法还是数据成员)。它应被视为实施细节,如有更改,恕不另行通知。
只能通过本类的非私有方法访问。
|
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
|
#-*- coding:UTF-8 -*-
class
parent:
count
=
100
;
__privateName
=
"zhansan"
;
def
__init__(
self
):
print
(
"fu init"
);
self
.age
=
10
;
self
.num
=
"12234"
;
self
.name
=
"fu"
;
def
setName(
self
,name):
print
(
"fulei setName"
);
self
.name
=
name;
def
getName(
self
):
print
(
"fulei getName"
);
return
self
.name;
def
getPrivateName(
self
):
return
self
.__privateName;
class
child(parent):
def
__init__(
self
):
parent.__init__(
self
);
print
(
"zilei init"
);
def
setName(
self
,name):
parent.setName(
self
,name);
print
(
"zilei setName"
);
def
getName(
self
):
print
(
"zilei getName"
);
return
parent.getName(
self
);
def
getPrivateName(
self
):
return
parent.getPrivateName(
self
);
a
=
child();
print
(a.getName());
print
a.count;
print
a.getPrivateName();
|
初始化类时,先进入子类__init__()方法,调用父类的__init__()构造方法,再
执行子类__init__()代码,完成初始化。
有同名函数时,子类对象调用子类函数。
子类没有调用的函数时,子类对象调用父类函数。
、
本文转自 matengbing 51CTO博客,原文链接:http://blog.51cto.com/matengbing/1904650
![B$FV_`}3I[2ZDJ_]J0{T47V.png wKioL1jAwRyhpKL6AAAotfNkK24920.png-wh_50](https://ucc.alicdn.com/gtdqzn4uqwgsg/developer-article498044/20241019/3fecc35e7d2b4da2b015f7ecab60d782.png?x-oss-process=image/resize,w_1400/format,webp)