返回多种类型
Bad code sampledef get_secret_code(password): if password != “bicycle”: return None return "42"1234Good code sampledef get_secret_code(password): if password != “bicycle”: raise ValueError return "42"1234如果有多种返回类型,会难为维护。最好只使用一种类型返回,空值或者找不到数据可以抛异常。在类的外面使用被保护的成员对象Bad code sampleclass Rectangle: def init(self, width, height): self._width = width self._height = heighttr = Rectangle(5, 6)memberprint( “Widht:{:d}”.format(r._width))123456789Good code sampleclass Rectangle: def init(self, width, height): self._width = width self._height = height @property def width(self): return self._widthtr = Rectangle(5, 6)memberprint( “Widht:{:d}”.format(r.width))12345678910111213在其他语言中,被保护的成员,在外部是无法被访问的。但是python里面,你还是可以访问。不过,这并不代表你就应该去访问。还是应该遵守软件开发的基本守则。
2021-10-09
最新推荐文章于 2021-10-09 20:07:47 发布