一、类和实例
__init__函数:相当于构造函数,定义之后创建新的对象不能不传参
二、访问限制
使用双下划线__将对象隐藏,相当于private
class Student(object):
def __init__(self, name, gender):
self.__name = name
self.__gender = gender
def get_name(self):
return self.__name
def get_gender(self):
return self.__gender
def set_gender(self, gender):
self.__gender = gender
bart = Student('Bart', 'male')
if bart.get_gender() != 'male':
print('测试失败!')
else:
bart.set_gender('female')
三、继承和多态
四、实例属性和类属性
如果Student 类本身需要绑定一个属性呢?可以直接在class中定义属性,这种属性是类属性,归Student 类所有:
class Student(object):
name = 'Student'
练习:
为了统计学生人数,可以给Student类增加一个类属性,每创建一个实例,该属性自动增加:?
class Student(object):
count = 0
def __init__(self, name):
self.name = name
Student.count = Student.count+1
# 测试:
if Student.count != 0:
print('测试失败!')
else:
bart = Student('Bart')
if Student.count != 1:
print('测试失败!')
else:
lisa = Student('Bart')
if Student.count != 2:
print('测试失败!')
else:
print('Students:', Student.count)
print('测试通过!')
?
|