本文主要是介绍小白学python之访问限制_学习笔记,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
本文以廖雪峰的官方网站为参考来学习python的。其学习链接为廖雪峰小白学python教程。
本文是学习到python的访问限制。参考链接廖雪峰python访问限制。
class Student(object):def __init__(self,name,score):self.__name= nameself.__score = scoredef print_score(self):print('%s: %s' % (self.__name, self.__score))bart = Student('Bart Simpson',59)
bart.__name
运行结果为 :
Traceback (most recent call last):
File "**********", line 11, in <module>
bart.__name
AttributeError: 'Student' object has no attribute '__name'
无法访问实例变量。
如果输入代码
bart.print_score()
则会得到结果:
Bart Simpson: 59
class Student(object):def __init__(self,name,score):self.__name= nameself.__score = scoredef print_score(self):print('%s: %s' % (self.__name, self.__score))def get_name(self):return self.__namedef get_score(self):return self.__scorebart.print_score()
print(bart.get_name())
print(bart.get_score())
输入上面代码可以得到:
Bart Simpson: 59
Bart Simpson
59
现在可以访问实例变量了。
class Student(object):def __init__(self,name,score):self.__name= nameself.__score = scoredef print_score(self):print('%s: %s' % (self.__name, self.__score))def get_name(self):return self.__namedef get_score(self):return self.__scoredef set_score(self,score):if 0 <= score <= 100:self.__score = scoreelse:raise ValueError('bad score')
输入代码:
bart.set_score(99)
bart.print_score()
print(bart.get_score())
可以得到:
Bart Simpson: 99
99
# -*- coding: utf-8 -*-
class Student(object):def __init__(self,name,gender):self.name = nameself.gender = genderdef get_gender(self):return self.gender;def set_gender(self,gender):self.gender = gender# 测试:
bart = Student('Bart', 'male')
print(bart.get_gender)
print(bart.get_gender())
print(type(bart.get_gender()))
print(type('male'))
if bart.get_gender() != 'male':print('测试失败!')print(bart.get_gender())
else:bart.set_gender('female')print(bart.get_gender())if bart.get_gender() != 'female':print('测试失败!')else:print('测试成功!')
以上为文章结尾测试题目和本人做的答案。
编译结果为
<bound method Student.get_gender of <__main__.Student object at 0x00000000021B1DD8>>
male
<class 'str'>
<class 'str'>
female
测试成功!
这篇关于小白学python之访问限制_学习笔记的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!