好友
阅读权限30
听众
最后登录1970-1-1
|
甜萝
发表于 2022-11-13 11:41
本帖最后由 paypojie 于 2022-11-13 12:27 编辑
类的私有化
前言 封装 定义私有化属性 定义公有 set get 方法
[Python] 纯文本查看 复制代码 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 | class Student():
def __init__( self ,name,age,score):
self .name = name
self .age = age
self .score = score
def __str__( self ):
return '%s %s %s' % ( self .name, self .age, self .score)
s = Student( 'Emma' , 18 , 59 )
print (s)
print (s.score)
|
 
[Python] 纯文本查看 复制代码 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | class Student():
def __init__( self ,name,age,score):
self .name = name
self .age = age
self .__score = score
def __str__( self ):
return '%s %s %s' % ( self .name, self .age, self .__score)
s = Student( 'Emma' , 18 , 59 )
print (s)
s.__score = 60
print (s)
|
 
[Python] 纯文本查看 复制代码 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 | class Student():
def __init__( self ,name,age,score):
self .name = name
self .age = age
self .__score = score
def __str__( self ):
return '%s %s %s' % ( self .name, self .age, self .__score)
def setScore( self ,score):
self .__score = score
s = Student( 'xiaoming' , 18 , 59 )
print (s)
s.setScore( 60 )
print (s)
|
 
[Python] 纯文本查看 复制代码 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 | class Student():
def __init__( self ,name,age,score):
self .name = name
self .age = age
self .__score = score
def __str__( self ):
return '%s %s %s' % ( self .name, self .age, self .__score)
def getScore( self ):
return self .__score
s = Student( 'xiaoming' , 18 , 59 )
print (s.getScore())
|
  
小结
私有化属性 在属性名前面加__ 属性就变成了私有属性 只能在类里面进行访问 外界是无法访问的
为了不让外界随意访问 定义公有set和get方法 可以允许修改和访问你指定的私有属性
不一定需要用setXxx getXxx 这种形式 这样写 只是为了见名知意
set和get方法里面用if...else 这种条件判断语句 将能够更好的指定访问和修改属性值的范围
最后看张截图 都是最顶级的开源大神 网站链接放在评论区 这里 不知道如何添加链接
|
免费评分
-
查看全部评分
|