So I am trying to learn how to properly set Class attributes of a Python class, and wondering about using class functions to do so.
My beginners way has taught me to do:
class MyClass:
"""MyClass class instance"""
def __init__(self, project, version, command):
self.project = project
self.__version = version
self.__command = command
"""Get version used"""
def getVersion(self):
return self.__version
"""Get command executed"""
def getCommand(self):
return self.__command
"""Set version used"""
def setVersion(self, version):
self.__version = version
This is fine and simple, but this means that I already know the values of my attributes when I instantiate MyClass, since I am passing them to create my object, or if I don't pass them I would use my beginners way of setVersion(version) after creating MyClass object. In my search I read this, which lead me to read about properties, and made me realize that I should not use getter/setters in Python but rather utilize properties. Is this correct?
However, I am wondering if it's Pythonic (or just even correct) to set some of the MyClass instance attributes (project, version, command) using a function. I want to do this because I want this class to do the work of finding these values from specific files by only passing 1 argument. This came to mind, but thought it might be wrong:
class MyClass:
"""MyClass class instance"""
def __init__(self, project):
self.project = project
self._version = self.version()
self._command = self.command()
"""Get version used"""
def version(self):
...
use `project` attribute here to get `version` from file...
...
return version
"""Get command executed"""
def command(self):
...
use `project` attribute here to get `command` from file...
...
return command
Is it even a logical way of setting instance variables by calling a class function?
Should I utilize properties in some ways instead?
Should I make a function outside the MyClass that finds these values returns a MyClass instance instead?
Is there a more proper Pythonic way?
I basically want to create an object with all the extra information (version, command, etc..) by just instantiating it with 1 passed attribute.
Thank you in advance!
c = MyClass(); c.version = 3, then that will continue to work (syntactically, anyway) if you changeversionto a property.