#由于Python是动态语言,根据类创建的实例可以任意绑定属性。
#给实例绑定属性的方法是通过实例变量,或者通过self变量:
#这一点不同于静态语言
class Student(object):
def __init__(self, name, gender):
self.name = name
self.age = 21
self.__gender = gender
def get_gender(self):
return self.__gender
def set_gender(self,gender):
if gender not in ['male','female']:
raise ValueError('bad gender')
self.__gender=gender
def get_age(self):
return self.age
# 测试:
bart = Student('Bart', 'male')
bart.grade = 100
if bart.get_gender() != 'male':
print('测试失败!')
else:
bart.set_gender('female')
if bart.get_gender() != 'female':
print('测试失败!')
else:
print('测试成功!')
L = dir(bart)
cnt = 0
for item in L:
print(item,end=' ')
cnt+=1
if cnt % 3 ==0:
print('')
print(bart.grade)
#类属性是类所有的,实例属性是类对应实例属性所有的
class Student(object):
count = 0
def __init__(self, name):
self.name = name
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('测试通过!')
class Screen(object):
@property
def width(self):
return self._width
@property
def height(self):
return self._height
@width.setter
def width(self,width):
self._width = width
@height.setter
def height(self,height):
self._height = height
@property
def resolution(self):
return self._height * self._width
# 测试:
s = Screen()
s.width = 1024
s.height = 768
print('resolution =', s.resolution)
if s.resolution == 786432:
print('测试通过!')
else:
print('测试失败!')
python练习2
最新推荐文章于 2023-04-27 22:53:09 发布