|
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) # iceprint(p.age) # 18print(p.gender) # 男print(hasattr(p, ‘weight‘)) # False# 为p添加weight属性p.weight = ‘70kg‘print(hasattr(p, ‘weight‘)) # Trueprint(getattr(p, ‘name‘)) # iceprint(p.__dict__) # {‘age‘: 18, ‘gender‘: ‘男‘, ‘name‘: ‘ice‘}print(Person.__name__) # Personprint(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.__idtemp = Demo()# print(temp.__id) # 报错 AttributeError: ‘Demo‘ object has no attribute ‘__id‘print(temp.getId()) # 123456print(temp._Demo__id) # 123456 |
原文:http://www.cnblogs.com/QI1125/p/7545537.html