python的面相对象中,拥有3个成员,字段、方法、属性
1 class Foo:
2 def __init__(self,name):
3 #公有字段name在类中与类外均能调用
4 self.name = name
5
6 def f1(self):
7 print(self.name)
8
9 obj = Foo('alex')
10 #内部调用
11 print(obj.name)
12 #>>>alex
13 #外部调用
14 obj.f1()
15 #>>>alex
1 class Foo:
2 def __init__(self,name):
3 #私有字段name只能在类中调用类外不能调用
4 self.__name = name
5
6 def f1(self):
7 print(self.__name)
8
9
10 obj = Foo('alex')
11 #内部调用
12 print(obj.name)
13 #>>>alex
14 #外部调用
15 obj.f1()
16 #>>>报错
1 #特殊成员
2 class Foo:
3 #构造方法
4 def __init__(self,name,age):
5 self.name =name
6 self.age = age
7 print('实例化对象时执行')
8
9 #析构方法
10 def __def__(self):
11 print('内存被释放时,自动触发执行')
12 def __call__(self):
13 print('call')
14
15 def __str__(self):
16 return '%s-%d'%(self.name,self.age)
17 return '返回什么就显示什么'
18 p=Foo()
19 >>>实例化对象时执行
20 #>>>显示对象属于哪个类
21 print(p.__class__)
22 >>><class '__main__.Foo'>
23 #执行call方法
24 p()
25 >>>call
26 #先执行构造方法在执行call方法
27 Foo()()
28 >>>实例化对象时执行
29 >>>call
30
31 obj1 = Foo('alex',71)
32 obj2 = Foo('eric',72)
33 #打印对象自动调用__str__方法
34 print(obj1)
35 >>>alex-71
36 print(obj2)
37 >>>eric-72
38 #执行str()方法的时候自动调用__str__方法
39 ret = str(obj1)
40 print(ret)
41 >>>alex-71
1 class Foo:
2 def __init__(self,name):
3 self.name = name
4
5
6 #显示对象下的字段,以字典的形式保存
7 obj1 = Foo('alex')
8 obj2 = Foo('ecic')
9 ret = obj1.__dict__
10 print(ret)
11 print(ret['name']
12 >>>{'name','alex'}
13 >>>alex
class Foo:
def __init__(self,name,age):
self.name = name
self.age =age
def __add__(self,other):
temp = '%s - %d'%(self.name,other.age)
return temp
#执行对象相加的时候自动执行__add__方法
obj1 = Foo('alex',71)
obj2 = Foo('ecic',72)
#将obj1传入__add__方法的self中,obj2传入other中
ret = obj1 + obj2
print(ret)
>>>alex - 72