防止更改实例变量

时间:2017-04-14 08:42:59

标签: python variables instance-variables

我想允许用户在实例化后更改self.path而不是任何其他实例变量。但是,如果更改self.path,则应重新评估其他实例变量。这可能吗?

class File(object):

    def __init__(self, path):
        self.path = os.path.abspath(path)
        self.name = os.path.basename(self.path)
        self.parent = os.path.dirname(self.path)

        self.extension = self._get_extension()
        self.category = self.get_category(self.extension)
        self.exists = os.path.isfile(self.path)

    def _get_extension(self):
        extension = None
        result = os.path.splitext(self.name)[1][1:]
        if result:
            extension = result
        return extension

    def get_category(self, extension):
        if extension:
            file_extension = extension.upper()
            for key in fileGroups.keys():
                common = set(fileGroups[key]) & set([file_extension])
                if common:
                    return key
        return 'UNDEFINED'

2 个答案:

答案 0 :(得分:1)

https://stackoverflow.com/a/598092/3110529开始,您正在寻找的是属性getter / setter模式。 Python通过@property@member.setter实现此功能,您可以在上面的答案示例中看到这一点。

就您的问题而言,您可以通过执行以下操作来解决问题:

class File(object):

    def __init__(self, path):
        self.__path = os.path.abspath(path)
        self.__name = os.path.basename(self.path)
        self.__parent = os.path.dirname(self.path)

        self.__extension = self._get_extension()
        self.__category = self.get_category(self.extension)
        self.__exists = os.path.isfile(self.path)

    @property
    def path(self):
        return self.__path

    @path.setter
    def path(self, value):
        self.__path = value
        # Update other variables here too

    @property
    def name(self):
        return self.__name

etc for the rest of your properties

这意味着您可以执行以下操作:

file = File("a path")
print(file.path)
file.path = "some other path"

# This will throw an AttributeError
file.name = "another name"

请注意,所有内容都相同,但如果尝试修改,则没有setter的属性会抛出错误。

这确实会使您的File类显着增大,但它会阻止用户更改path以外的成员,因为没有实现setter。从技术上讲,用户仍然可以file.__path = "something else",但通常会理解前缀为双下划线的成员是私人的,不应该被篡改。

答案 1 :(得分:1)

Dilanm是对的。如果需要将成员变量设置为只读或在访问使用属性上添加验证或其他任务。请注意,类声明中的(对象)是可选的,因为没有办法在python类中强制执行私有成员,所以我只想用'_'强调我的意图,除非你真的有'__'的理由。

#!/usr/bin/env python3

import os.path

class File:
    def __init__(self, path):
        self._path = path
        self.compute_others()

    def compute_others(self):
        self._parent = os.path.dirname(self._path)
        pass # add other attributes to be computed

    # getter, also makes .path read-only
    @property
    def path(self):
        return self._path

    # setter, allows setting but adds validation or other tasks
    @path.setter
    def path(self, path):
        self._path = path
        self.compute_others()

    # other attributes only have getters (read-only)
    @property
    def parent(self):
        return self._parent

    def __str__(self):
        return 'path:{}\nparent:{}\n\n'.format(self.path, self.parent)

f = File('/usr')
print(f)

f.path = '/usr/local'
#f.parent = '/tmp' # error, read-only property
print(f)

要覆盖成员,只需在子类中再次定义它。属性也不例外。

相关问题