what does it mean by defining a variable with double underscore only at the prefix part ?
like in this example at pastebin i.e. self.__weakReference

Recommended Answers

All 3 Replies

Here is an example ...

''' class_private101.py
class variables and methods can be made private to the class
'''

class C(object):
    '''
    inheriting object is automatic in Python3
    '''
    # k is public to all instances of class C
    k = 1234
    # variable names with double underline prefix like
    # __m or __m_ will be private to the class
    # (now Python uses _classname__m here _C__m internally)
    __m = 5678
    # _n or _n_ or _n__ or __n__ will be public
    __n__ = 999

    def __init__(self, v):
        '''
        __init__() will be used first, if it's there
        '''
        self.value = v

    def add(self, x):
        return self.value + x

    def __subtract(self, y):
        '''
        double underline prefix makes this method private to class
        '''
        return self.value - y

    def deduct(self, y):
        return self.__subtract(y)


a = C(7)    # implies C.__init__(a, 7)
print(C)    # <class '__main__.C'>
print(a)    # <__main__.C object at 0x009FCB50>

print(a.add(2))     # 9
print(a.deduct(4))  # 3
print(a.value)      # 7
print(a.k)          # 1234
print(a.__n__)      # 999

# note that variable __m and
# method __subtract() are private to the class and
# give AttributeError: 'C' object has no attribute '__m'
# or AttributeError: 'C' object has no attribute '__subtract'
#print(a.__m)
#print(a.__subtract(4))

Note:
Don't overdo private class variables and methods too much, since they will not be inherited by other classes.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.