Home > Software design >  Can there be class attributes accessible only by specific class instance [Python]
Can there be class attributes accessible only by specific class instance [Python]

Time:08-09

Is it possible to define a class which has attributes that are visible and accessible by only specific type of class and maybe even only specific instance of a specific type of class.

Example: I would like to define a class (class A) which hold and controls some resources. There will be another class (class B) which has some data/state information and that would need to use resources hold by class A. So user API would be to define only one class A and then multiple class B instances which they can add/register to class A instance. Is it possible to make it so that some attributes and methods of class B instances are only visible/accessible by class A instance and not by the user? E.g. if there is a an attribute holding some datetime value then only class A instance could access that, but user directly can't.

EDIT: I know I can make those attributes and methods 'private' and in that way kind of achieve what I want. But this goes against the concept of private attributes/methods (they are still used externally by some). Also, I am hoping that maybe there is a more elegant (pythonic) way of achieving this.

CodePudding user response:

No, it's not possible to do this. Either an attribute can be accessed or it can't. Other than private attributes, which can only be accessed within the same class (unless you mangle the name by hand), there's no access control based on where the attribute reference is.

  • Related