将它们定义为类变量可能是最面向未来的方法,因为您以后可以使用依赖注入来更改这些变量,这对于单元测试非常有用。例如:
class Server:
def __init__(self, url, icon):
self.url = url
self.icon = icon
server = Server('url.com', 'file.ico')
# in your tests, you may want to use a different ico/url
test_server = Server('url.com', 'test_icon.ico')
关于 getter 和 setter 的说明:
另请注意,在 Python 中往往会避免使用 getter 和 setter,如果需要验证,或者需要重构具有大量依赖代码的类,则使用属性来代替。在 Java 和 C 等预编译语言中,getter/setter 用于封装,以便以后可以更改实现,但在 Python 中为了性能和清晰度而避免使用。因此,首先,变量可以正常访问,如果实现发生变化,您可以使用and装饰器,以便使用 getter 和 setter,即使您似乎是直接访问变量。@property
@variable.setter
所以原本可以icon
直接访问。
print(server.icon)
但是让我们稍后说您icon
将类内部重构为_icon_file
并_icon_image
在每次设置文件时加载文件,但您的应用程序的其余部分需要该icon
变量。这就是 getter 和 setter 通常的用途(以及对设置变量的任何检查/转换),因此我们现在可以为 添加 getter 和 setter icon
,即使icon
变量不再存在:
class Server:
def __init__(self, url, icon_filename):
self.url = url
self._icon_filename = icon_filename
self._icon_image = self._load_icon(icon_filename)
@property
def icon(self):
"""
Get the icon file name
@returns str of the icon filename
"""
return self._icon_filename
@icon.setter
def icon(self, icon_filename):
"""
Load a new icon file as the icon
@param icon_filename the relative path to the icon file
"""
if icon_filename[-4:] != '.ico':
raise Exception('Must be of .ico format')
self._icon_filename = icon_filename
self._icon_image = self._load_icon(icon_filename)
def _load_icon(self, icon_filename):
"""
Load a .ico file, and maybe do some other stuff
@returns Image of the loaded icon
@private
"""
# implementation here...
server = Server('url.com', 'file.ico')
print(server.icon) # file.ico
server.icon = 'icon2.ico' # sets and loads new icon
print(server.icon) # icon2.ico
server.icon = 'icon3.jpg' # throws an exception