bre*_*ics 7 python oop class python-3.x
所以我试图学习如何正确设置Python类的Class属性,并想知道如何使用类函数来实现.
我的初学者方式教我做:
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
Run Code Online (Sandbox Code Playgroud)
这很简单,但这意味着当我实例化MyClass时我已经知道了我的属性的值,因为我传递它们来创建我的对象,或者如果我没有传递它们,我会setVersion(version)在创建后使用我的初学者方式MyClass对象.在我的搜索中,我阅读了这篇文章,它让我了解了属性,并让我意识到我不应该在Python中使用getter/setter而是使用属性.它是否正确?
但是,我想知道是否使用函数设置一些MyClass实例属性(项目,版本,命令)是Pythonic(或者甚至是正确的).我想这样做是因为我希望这个类只通过传递1个参数来完成从特定文件中查找这些值的工作.想到这一点,但认为这可能是错的:
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
Run Code Online (Sandbox Code Playgroud)
它甚至是通过调用类函数来设置实例变量的逻辑方法吗?
我应该在某些方面利用属性吗?
我应该在MyClass之外创建一个找到这些值的函数来返回一个MyClass实例吗?
有更合适的Pythonic方式吗?
我基本上想要通过使用1个传递属性实例化它来创建一个包含所有额外信息(版本,命令等)的对象.
先感谢您!
有很多方法可以解决这个问题,但这就是我通常的做法:
class MyClass:
"""MyClass class instance"""
def __init__(self, project, version, command):
self.project = project
self.version = version
self.command = command
@classmethod
def from_file(cls, project):
"""
Alternate constructor that takes a project
and extracts the other attributes from a file
"""
#... some code to use `project`
#... and get `version` and `command` from file
return cls(project, version, command)
# usage
m = MyClass.from_file('project01')
Run Code Online (Sandbox Code Playgroud)
classmethod是一个装饰器,它使一个方法能够直接在类中调用,而不是实例.然后该方法将自动将类作为第一个参数.
cls只是一个名称意味着类,就像我们self用于实例,但我们可以真正使用任何名称.主对象构造函数__init__采用完整参数,但新from_file类方法作为替代构造函数,通过创建类的实例并返回它.
请注意,这不是一个明确的答案,而只是建议采用pythonic方法来解决它.