Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private Class Variables in Python?

Tags:

python

class

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?

like image 837
Ray Salemi Avatar asked Apr 06 '26 00:04

Ray Salemi


1 Answers

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)
like image 132
Yevhen Kuzmovych Avatar answered Apr 08 '26 12:04

Yevhen Kuzmovych



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!