Defining them as class variables is probably the most future-proof method, as you could later use dependency injection to change these variables, which is very useful for unit testing. For example:
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')
A note on getters an setters:
Also note that getters and setters tend to be avoided in Python, and properties are used instead if validation is required, or a class with lots of dependent code is refactored. In precompiled languages such as Java and C, the getters/setters are used for encapsulation so that the implementation can later be changed, but in Python are avoided for performance and clarity. So to start with, variables can be accessed as normal, and if the implementation ever changes you can then use the @property
and @variable.setter
decorators so that getters and setters are used, even though you appear to be accessing the variable directly.
So originally you can access icon
directly.
print(server.icon)
But lets say later you refactor your icon
inside the class to be _icon_file
and _icon_image
and load the file every time it's set, but the rest of your app expects the icon
variable. This is what getters and setters are usually for (alongside any checks/conversion on setting variables), so we can now add getters and setters for icon
, even though the icon
variable no longer exists:
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