getnum java_2018年最新最新黑马java十次方社交项目教程

在class中self表示类实例,即class object,

class NUM:

def prt(self):

print(self)

print(self.__class__)

num1=NUM();

num2.prt()

输出:

可见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 "", line 1, in

obj=ClassName()

TypeError: __init__() takes 0 positional arguments but 1 was given

---------------------

作者:east1203

来源:CSDN

原文:https://blog.csdn.net/m0_38037810/article/details/84955020

版权声明:本文为博主原创文章,转载请附上博文链接!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值