Uh oh!
There was an error while loading. Please reload this page.
forked from SergioJune/python_test
- Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtest22.py
More file actions
Latest commit
108 lines (82 loc) · 2.66 KB
/
Copy pathtest22.py
File metadata and controls
108 lines (82 loc) · 2.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'练习面向对象高级特性的@property'
__author__='sergiojune'
classStudent(object):
def__init__(self, name, score):
self.__name=name
self.__score=score
defget_name(self):
returnself.__name
defget_score(self):
returnself.__score
defset_name(self, name):
ifnotisinstance(name, str):
raiseValueError('请输入正确的名字')
self.__name=name
defset_score(self, score):
ifscore<0orscore>100:
raiseValueError('请输入正确的成绩')
elifnotisinstance(score, int):
raiseValueError('请输入正确的成绩')
else:
self.__score=score
stu=Student('bob', 86)
print(stu.get_name())
# 这个就会报错
# stu.set_score(999)
# 使用@property装饰器
classPeople(object):
def__init__(self, name, age):
self.__name=name
self.__age=age
@property# 添加装饰器,让这个方法变成一个属性
defage(self):
returnself.__age
@property
defname(self):
returnself.__name
@name.setter# 这个前缀名字要和property装饰器的方法名字一致
defname(self, name):
ifnotisinstance(name, str):
raiseValueError('请输入正确名字')
self.__name=name
p=People('bart', 20)
# 加了装饰器之后这样直接调用属性
print(p.name) # 这个就是直接获取name属性
p.name='bat'# 直接修改属性
print(p.name)
print(p.age)
# 由于age只是只读,不予许写,所以这个会报错
# p.age = 52
# 作业:请利用@property给一个Screen对象加上width和height属性,以及一个只读属性resolution
classScreen(object):
def__init__(self):
self.__width=None
self.__height=None
@property
defwidth(self):
returnself.__width
@property
defheight(self):
returnself.__height
@width.setter
defwidth(self,width):
ifwidth<0orwidth>1000:
raiseValueError('请输入正确的宽')
self.__width=width
@height.setter
defheight(self, height):
ifheight<0orheight>1000:
raiseValueError('请输入正确的高')
self.__height=height
@property
defresolution(self):
self.__resolution= (self.__height, self.__width)
returnself.__resolution
screen=Screen()
screen.width=25
screen.height=65
print(screen.width)
print(screen.height)
print(screen.resolution)