防止更改实例变量 [英] Prevent altering instance variable

查看:61
本文介绍了防止更改实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to allow the user to change self.path after instantiation but not any other instance variable. However, if self.path is changed then the other instance variables should be reevaluated. Is this possible?

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'

推荐答案

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

From https://stackoverflow.com/a/598092/3110529 what you're looking for is the property getter/setter pattern. Python implements this via @property and @member.setter, you can see this in the example of the answer above.

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

In terms of your issue you can solve it by doing the following:

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

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

This means you can do stuff like:

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

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

请注意,所有工作原理都相同,但是如果尝试修改不带setter的属性,则会抛出错误.

Note that everything works the same but properties without setters will throw errors if tried to be modified.

这确实使您的File类明显变大,但是由于没有实现设置器,因此它阻止了用户更改path以外的成员.从技术上讲,用户仍然可以执行file.__path = "something else",但是通常可以理解,以双下划线为前缀的成员是私有的,不应被篡改.

This does make your File class significantly larger, but it prevents the user from changing members other than path as there is no setter implemented. Technically the user can still do file.__path = "something else" but there's generally an understanding that members prefixed with double underscores are private and shouldn't be tampered with.

这篇关于防止更改实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆