class Student(object):
# 在__init__方法中,将name、score变量属性直接绑定进来
def __init__(self,name,score):
self.name=name
self.score=score
chloe=Student('Chloe',60)
print(chloe.name,chloe.score)
运行结果:
数据封装&增加新方法
class Student(object):
# 在__init__方法中,将name、score变量属性直接绑定进来
def __init__(self,name,score):
self.name=name
self.score=score
def print_score(self):
print('%s:%s' % (self.name, self.score))
# 增加新方法
def get_grade(self):
if self.score>90:
return 'A'
else:
return 'B'
chloe = Student('Chloe', 60)
print(chloe.print_score())
print(chloe.get_grade())
访问权限
before
class Student(object):
# 在__init__方法中,将name、score变量属性直接绑定进来
def __init__(self,name,score):
self.name=name
self.score=score
def print_score(self):
print('%s:%s' %(self.name, self.score))
chloe=Student('Chloe',99)
print(chloe.name)
after
class Student(object):
# 在__init__方法中,将name、score变量属性直接绑定进来
def __init__(self,name,score):
self.__name=name
self.__score=score
def print_score(self):
print('%s:%s' %(self.__name, self.__score))
chloe=Student('Chloe',99)
print(chloe.__name)
class Student1(object):
def __init__(self,name,gender):
self.name=name
self.__gender=gender
# 允许外部访问
def get_gender(self):
return self.__gender
# 允许外部更改
def set_gender(self,gender):
self.__gender=gender
bart=Student1('songjiang','female')
bart=Student1('SJ','male')
print(bart.name,bart.get_gender())