当前位置:   article > 正文

python中self用法小结_python self的用法

python self的用法

在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.属性

  1. class NUM:
  2. num=0
  3. def init(self):
  4. self.num+=1
  5. def getnum(self):
  6. print ("the self. num is",self.num)
  7. num1=NUM();
  8. num1.init()
  9. num1.getnum()
  10. num2=NUM()
  11. num2.init()
  12. 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,,):

     类名.属性

  1. class NUM:
  2. num=0
  3. objnum=0
  4. def init(self):
  5. self.num+=1
  6. NUM.objnum+=1
  7. def getnum(self):
  8. print ("the self. num is",self.num)
  9. def getobjcnt(self):
  10. print("with self arg,the NUM.num is ",NUM.objnum)
  11. num1=NUM();
  12. num1.init()
  13. num1.getnum()
  14. num1.getobjcnt()
  15. num2=NUM()
  16. num2.init()
  17. num2.getnum()
  18. 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参数,函数中,类调用属性,函数用类名调用

  1. class NUM:
  2. num=0
  3. objnum=0
  4. def init(self):
  5. self.num+=1
  6. NUM.objnum+=1
  7. def getnum(self):
  8. print ("the self. num is",self.num)
  9. def getobjcnt(self):
  10. print("with self arg,the NUM.num is ",NUM.objnum)
  11. def Getobjcnt():
  12. print("without self arg,the NUM.num is",NUM.objnum)
  13. num1=NUM();
  14. num1.init()
  15. num1.getnum()
  16. num1.getobjcnt()
  17. NUM.Getobjcnt()
  18. num2=NUM()
  19. num2.init()
  20. num2.getnum()
  21. num2.getobjcnt()
  22. 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

 

 

 

 

 

 

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号