版权声明:本文博主原创,转载请注明出处,感谢您的合作! https://blog.csdn.net/Thanlon/article/details/89417554
1、控制类中返回字符串的方法:__ str __
# coding:utf8
class CustomClass:
def __init__(self, name):
self.name = name
# 控制类中返回字符串的方法
def __str__(self):
print('First executing the method,then executing the print operation!')
return 'Hello ' + self.name + '!'
print(CustomClass('Thanlon'))
2、使用 @property简化get和set方法
# coding:utf8
import traceback
class Stu:
@property
def score(self):
return self._score
@score.setter
def score(self, value):
if not isinstance(value, int):
raise ValueError('not int')
elif value < 0 or value > 100:
raise ValueError('not between 0 and 100')
self._score = value
@property
def double_score(self):
return self._score * 2
stu = Stu()
stu.score = 99
print(stu.score)
# try:
# stu.score = '100'
# except ValueError:
# traceback.print_exc()
# except Exception:
# traceback.print_exc()
# try:
# stu.score = -1
# except ValueError:
# traceback.print_exc()
# except Exception:
# traceback.print_exc()
print(stu.double_score)
#实现只读属性
# setter will be failed,double_score,property is only read
try:
stu.double_score = 100
except AttributeError:
traceback.print_exc() # 报错信息:AttributeError: can't set attribute
例:利用@property给Screen对象加上可读可写的width和height属性、以及一个只读属性resolution。
class Screen:
@property
def width(self):
return self._width
@width.setter
def width(self, value):
self._width = value
@property
def height(self):
return self._height
@height.setter
def height(self, value):
self._height = value
@property
def resolution(self):
return self._resolution