Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Friend"ing classes in python

Is there any way to make certain variables in classes "private" (or whatever self.__var really is) but be accessible to another class, like friends in c++, except in python? I do not want the variables in either class being messed with. Nor do I want to copy the entire code over and convert it for the second class.

like image 572
calccrypto Avatar asked Jun 14 '11 03:06

calccrypto


People also ask

What is friend class explain with examples?

Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful to allow a particular class to access private members of other class. For example, a LinkedList class may be allowed to access private members of Node.

What is the difference between friend and friend class?

A friend function is used for accessing the non public member of a class. A class can allow non-member function and other classes to access its own private data by making them friend A Friend class has full access of private data members of another class without being member of that class.

What is the syntax of friend class?

A friend function in C++ is defined as a function that can access private, protected and public members of a class. The friend function is declared using the friend keyword inside the body of the class. Friend Function Syntax: class className { ... .. ...

What is the difference between inheritance and friend class?

Inheritance and Friendship in C++ Difference between Inheritance and Friendship in C++: In C++, friendship is not inherited. If a base class has a friend function, then the function doesn't become a friend of the derived class(es).


2 Answers

No, there is not such an option.

Use names that start with single underscores and tell the other people working on your project to not be silly about what they access.

like image 107
Amber Avatar answered Sep 22 '22 15:09

Amber


The philosophy of Python is that issues like access control are up to programmer discipline. It doesn't attempt to encode in the language which parts of the program are internal implementation details, and which are part of the documented interface. Thus, it doesn't need constructs like friend to try to declare which other parts of the program are part of the implementation of a class and which are merely clients.

The idea is that if you can't write/design/document/use good code without partially encoding these concepts into your program, you probably can't do it when you are encoding them either. Therefore it's better not to have such constructs in the language, since they don't increase the expressive power of the language and occasionally they get in the way.

like image 45
Ben Avatar answered Sep 22 '22 15:09

Ben