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
|
class
Person:
"Person類"
def
__init__(
self
, name, age, gender):
print
(
'進入Person的初始化'
)
self
.name
=
name
self
.age
=
age
self
.gender
=
gender
print
(
'離開Person的初始化'
)
def
getName(
self
):
print
(
self
.name)
p
=
Person(
'ice'
,
18
,
'男'
)
print
(p.name)
# ice
print
(p.age)
# 18
print
(p.gender)
# 男
print
(
hasattr
(p,
'weight'
))
# False
# 爲p添加weight屬性
p.weight
=
'70kg'
print
(
hasattr
(p,
'weight'
))
# True
print
(
getattr
(p,
'name'
))
# ice
print
(p.__dict__)
# {'age': 18, 'gender': '男', 'name': 'ice'}
print
(Person.__name__)
# Person
print
(Person.__doc__)
# Person類
print
(Person.__dict__)
# {'__doc__': 'Person類', '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__init__': <function Person.__init__ at 0x000000000284E950>, 'getName': <function Person.getName at 0x000000000284EA60>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__module__': '__main__'}
print
(Person.__mro__)
# (<class '__main__.Person'>, <class 'object'>)
print
(Person.__bases__)
# (<class 'object'>,)
print
(Person.__module__)
# __main__
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
class
Person:
def
__init__(
self
, name, age, gender):
print
(
'進入Person的初始化'
)
self
.name
=
name
self
.age
=
age
self
.gender
=
gender
print
(
'離開Person的初始化'
)
def
getName(
self
):
print
(
self
.name)
# Person實例對象
p
=
Person(
'ice'
,
18
,
'男'
)
print
(p.name)
print
(p.age)
print
(p.gender)
p.getName()
# 進入Person的初始化
# 離開Person的初始化
# ice
# 18
# 男
# ice
|
1
2
3
4
5
6
7
8
|
class
Demo:
__id
=
123456
def
getId(
self
):
return
self
.__id
temp
=
Demo()
# print(temp.__id) # 報錯 AttributeError: 'Demo' object has no attribute '__id'
print
(temp.getId())
# 123456
print
(temp._Demo__id)
# 123456
|