Should I use “self” to define variables / objects of class instanced which I will not need to reach from the outside?

前端 未结 3 767
春和景丽
春和景丽 2021-02-06 10:14

I am not a complete beginner but fairly new to Python. Whilst working on a project today I just had an idea and wondered regarding the usage of \"self

3条回答
  •  没有蜡笔的小新
    2021-02-06 10:59

    Python does not really distinguish "public" from "private" variables. Anything you assign to a name in self using 'self.something = value' will be an instance variable for that instance.

    Python does have two conventions that are relevant here:

    1) Python fields or methods are prefixed with underscores('_') to tell users 'this is not a concern outside this class'. A single underscore is a conventional way of identifying more or less what a language like C# would call a 'protected' variable: it's internal to the implementation and should be left alone except by this class and derived classes. A double underscore is like a C# 'private' variable: it's internal and should be left alone even by derived classes, it can't be overridden

    class Example(object):
        def __init__(self)
           self._protected= "protected"
           self.__private = "private"
           self.public = "public"
    
    class Derived(Example):
        pass
    
    d = Derived()
    print d._protected
    >> protected
    print d.__private
    >> AttributeError: 'Derived' object has no attribute '__private'
    

    Strictly speaking the single underscore is just a typographical convention. The double underscore does actually mangle the name inside the class to prevent inheritance.

    2) You example is potentially case for using the property decorator if AnotherClass is actually going to hang around, and if manipulating the AnotherClass instance affects the state of AnotherClass.

    class C:
        def __init__(self, parent = None):
            super(C, self).__init__(parent)
            self._private = AnotherClass()
    
        @property
        def public(self):
           return self._private.some_method_on_AnotherClass()
    
        @public.setter
        def set_pub(self, val)
           self._private.set_value_on_AnotherClass(val)
    

提交回复
热议问题