python3 类的属性方法封装继承及小实例
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python3 类的属性方法封装继承及小实例相关的知识,希望对你有一定的参考价值。
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 |
以上是关于python3 类的属性方法封装继承及小实例的主要内容,如果未能解决你的问题,请参考以下文章