Ray Salemi
Ray Salemi

Reputation: 5933

Private Class Variables in Python?

I'd like to be able to extend a class without inheriting one of the class variables.

Given this scenario:

class A:
    aliases=['a','ay']

class B(A):
    pass

print(B.aliases)

I would rather get an error that B has not defined the aliases variable rather than have B accidentally called ay.

One could imagine a solution where aliases becomes a member of the instantiated object (self.aliases) and is set in __init__ but I really want to be able to access the aliases using the cls object rather than an instance of the class.

Any suggestions?

Upvotes: 3

Views: 107

Answers (2)

Yevhen Kuzmovych
Yevhen Kuzmovych

Reputation: 12140

Python does not have REALY private attributes. But you can define it with a double underscore (__):

class A:
    __aliases=['a','ay']

class B(A):
    pass

print(B.__aliases) # yields AttributeError

But you still will be able to access it with:

print(B._A__aliases)

Upvotes: 5

kpie
kpie

Reputation: 11120

This is kindof a ganky work around but here you go:

class K:
    def __init__(self):
        self.mems = dir(self)

def defaultMembers():
    k = K()
    return(k.mems)

class A:
    aliases=['a','ay']

class B(A):
    def __init__(self):
        for k in set(dir(self))-set(defaultMembers()):
            print("removing "+k)
            setattr(self, k, None)

a = A()
b = B()
print(b.aliases)
#None
print(a.aliases)
#['a','ay']

I guess all you really need is the setattr(self, "aliases", None) still this results in a None and not a non-variable. Unfortunately calsses don't support deletion because I tried to use del first.

Upvotes: 2

Related Questions