赞
踩
在class中self表示类实例,即class object,
class NUM:
def prt(self):
print(self)
print(self.__class__)
num1=NUM();
num2.prt()
输出:
<__main__.NUM object at 0x06387D90>
<class '__main__.NUM'>
可见self是类对象,self.__class__是类
1)用法一
self出现在函数的第一个参数处,并且用self调用属性
function_name(self,other aurgument,,):
self.属性
- class NUM:
- num=0
- def init(self):
- self.num+=1
- def getnum(self):
- print ("the self. num is",self.num)
- num1=NUM();
- num1.init()
- num1.getnum()
- num2=NUM()
- num2.init()
- num2.getnum()
-
-
'运行
the self. num is 1
the self. num is 1
输出的num变量都是1,并没有累加,这是因为每个对象有自己单独的num。
因为函数getnum()中有类对象参数——self,所以必须时类对象调用getnum(),num1.getnum()
如果是类调用getnum(),NUM.getnum()则出错,如下
TypeError: getobjcnt() missing 1 required positional argument: 'self'
提示少了一个参数
如果要用NUM.getnum(),则这样定义def getnum():,,,,,,不要加self
2)用法二
self出现在函数的第一个参数处,并且用类名调用属性
function_name(self,other aurgument,,):
类名.属性
- class NUM:
- num=0
- objnum=0
- def init(self):
- self.num+=1
- NUM.objnum+=1
- def getnum(self):
- print ("the self. num is",self.num)
- def getobjcnt(self):
- print("with self arg,the NUM.num is ",NUM.objnum)
- num1=NUM();
- num1.init()
- num1.getnum()
- num1.getobjcnt()
- num2=NUM()
- num2.init()
- num2.getnum()
- num2.getobjcnt()
-
'运行
the self. num is 1
with self arg,the NUM.num is 1
the self. num is 1
with self arg,the NUM.num is 2
用类名调用的属性作为类的属性,各个类对象共享
因为函数定义中有self参数,所以调用时用对象调用
方法三
没有self参数,函数中,类调用属性,函数用类名调用
- class NUM:
- num=0
- objnum=0
- def init(self):
- self.num+=1
- NUM.objnum+=1
- def getnum(self):
- print ("the self. num is",self.num)
- def getobjcnt(self):
- print("with self arg,the NUM.num is ",NUM.objnum)
- def Getobjcnt():
- print("without self arg,the NUM.num is",NUM.objnum)
- num1=NUM();
- num1.init()
- num1.getnum()
- num1.getobjcnt()
- NUM.Getobjcnt()
- num2=NUM()
- num2.init()
- num2.getnum()
- num2.getobjcnt()
- NUM.Getobjcnt()
'运行
the self. num is 1
with self arg,the NUM.num is 1
without self arg,the NUM.num is 1
the self. num is 1
with self arg,the NUM.num is 2
without self arg,the NUM.num is 2
用法四、self用在类的构造函数中
>>> class ClassName:
def __init__(self):
print("The object is created!")
>>> obj=ClassName()
The object is created!
如果去掉self
>>> class ClassName:
def __init__():
print("The object is created!")
报错:
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
obj=ClassName()
TypeError: __init__() takes 0 positional arguments but 1 was given
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。