如何在类中自动生成属性

时间:2018-12-04 01:17:10

标签: python-3.x class getter-setter setter

问题

目标是在给定路径和文件名的情况下自动构建完整的路径+名称字符串。

推荐:感谢@Patrick Haugh。

错误

以下代码失败

mySource = cls_Source_file.Source_file( )
mySource.file_path = "/Volumes/aqua/data/"
mySource.file_name = "short.rst"
print( "mySource.path_name = %s", mySource.path_name )


$ python laboratory.py 
self._path_name = self._file_path + self._file_name
TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'

laboratory.py中的类定义

class Source_file( object ):
    def __init__(self):
        self._file_name = None
        self._file_path = None
        self._path_name = None

    @property
    def file_name( self ):
        """Name of source file."""
        print( "getter of file_name called: self._file_name = ", self._file_name )
        return self._file_name

    @property
    def file_path( self ):
        """Path (absolute) to source file."""
        print( "getter of file_path called: self._file_path = ", self._file_path )
        return self._file_path

    @property
    def path_name( self ): # https://stackoverflow.com/questions/10381967/how-does-the-python-setter-decorator-work
        """File path and name."""
        print( "getter of file_path called: self._path_name = ", self._path_name )
        return self._path_name

    @file_name.setter
    def file_name( self, value ):
        print("setter of _file_name called: self._file_name = ", value )
        self._file_name = value

    @file_path.setter
    def file_path( self, value ):
        print("setter of _file_path called: self._file_path = ", value )
        self._file_path = value

    @path_name.setter
    def file_path( self, value ):
        self._path_name = self._file_path + self._file_name
        print("setter of _file_path called: self._file_path = ", self._path_name )

环境

sys.python = '3.7.0 (default, Jun 28 2018, 07:39:16) \n[Clang 4.0.1 (tags/RELEASE_401/final)]'

问题

如何添加path_name = file_path + file_name

0 个答案:

没有答案