在class内部,可以有属性和方法,而外部代码可以通过直接调用实例方法来操作数据,
这样,就隐藏了内部的复杂
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def print_score(self):
print '%s: %s' % (self.name, self.score)
bart = Student('Bart Simpson', 98)
print bart.name
print bart.score
bart.score = 59
print bart.score
C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/a2.py
Bart Simpson
98
59
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def print_score(self):
print '%s: %s' % (self.name, self.score)
bart = Student('Bart Simpson', 98)
print bart.name
C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/a2.py
Bart Simpson
class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = score
def print_score(self):
print '%s: %s' % (self.__name, self.__score)
bart = Student('Bart Simpson', 98)
print bart.name
C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/a2.py
Traceback (most recent call last):
File "C:/Users/TLCB/PycharmProjects/untitled/a2.py", line 10, in <module>
print bart.name
AttributeError: 'Student' object has no attribute 'name'
Process finished with exit code 1