Python32之类和对象2(self参数及魔法方法)

一、类方法中的self参数含义

  在Python中类的方法都要有self参数,其实质为对类的实例化对象的绑定从而使得在类的实例化对象调用方法时能够确认出是对哪个对象进行操作。

  带self的的参数是人家实例自身的,不带self的,爱谁谁,实例不管

  若是带了self,则可以在一个类中实现跨方法调用,以下例子中,我们使用a.climb()实现对self.x的定义,所以这就是为什么需要现有构造函数(初始化函数__init__)(即先把所有类中的参数全部定义以后,才能调用)

  注:不一定说一定要使用self,我们也可以使用其它的符号,比如使用“我的世界”代替“self”参数也是一样的

 1 class KK:
 2     x = 8
 3     def climb(self):
 4         self.x = 6
 5     def run(self):
 6         y = 5*self.x
 7         print(y)
 8 
 9         
10 >>> a = KK()
11 >>> a.run()
12 40
13 >>> a.climb()
14 >>> a.run()
15 30
16 >>> class KK:
17     def climb(self):
18         self.x = 6
19     def run(self):
20         y = 5*self.x
21         print(y)
22 
23         
24 >>> a = KK()
25 >>> a.climb()
26 >>> a.run()
27 30
View Code
 1 class KK:
 2     x = 8
 3     def climb(我的世界):
 4         我的世界.x = 6
 5     def run(我的世界):
 6         y = 5*我的世界.x
 7         print(y)
 8 
 9         
10 >>> a = KK()
11 >>> a.climb()
12 >>> a.run()
13 30
View Code

二、Python的魔法方法——构造方法(构造函数)

  def __init__(self,参数)   这个函数会在实例化类对象时自动调用该方法,这些方法若没有定义则系统自动生成,定义这些方法必须在方法名的左右两侧加上双下划线。

 1 a = KK()
 2 >>> a.climb()
 3 >>> a.run()
 4 30
 5 >>> class KK:
 6     def __init__(我的世界):
 7         我的世界.x = 6
 8     def run(我的世界):
 9         y = 5*我的世界.x
10         print(y)
11 
12         
13 >>> a = KK()
14 >>> a.run()
15 30
16 >>> class KK:
17     def climb(我的世界):
18         我的世界.x = 6
19     def run(我的世界):
20         y = 5*我的世界.x
21         print(y)
22 
23         
24 >>> a = KK()
25 >>> a.run()
26 Traceback (most recent call last):
27   File "<pyshell#127>", line 1, in <module>
28     a.run()
29   File "<pyshell#125>", line 5, in run
30     y = 5*我的世界.x
31 AttributeError: 'KK' object has no attribute 'x'
View Code

三、Python的公有私有成员设置

  严格来说,在Python里面的方法和属性都是公有的,但是可以通过名字转置的方法做出假私有的方法。

  设置假私有的方法很简单,只需要在变量或者方法前面加上双下划线即可,这样我们就没有办法直接对其进行访问

  注:我们可以使用“对象名._类名.成员名” 对其进行访问

 1 class KK:
 2     name = 'kst'
 3     __age = 18
 4     
 5 >>> a = KK()
 6 >>> print('我的年龄是%d'%a.__age)
 7 Traceback (most recent call last):
 8   File "<pyshell#138>", line 1, in <module>
 9     print('我的年龄是%d'%a.__age)
10 AttributeError: 'KK' object has no attribute '__age'
11 
12 >>> print('我的年龄是%d'%a._KK__age)
13 我的年龄是18
View Code
原文地址:https://www.cnblogs.com/ksht-wdyx/p/11369188.html