0

I realized that in many languages I have learned includes the keywords public and private, and I also found out that Lua's equivalent to private is local which got me thinking if there is also an equivalent in C and Python.

So is there an actual equivalent of Java's public and private in C and Python?

2 Answers2

3

There is a naming convention for protected and private fields in Python: A prefix of one underscore means protected, two underscores mean private. But this is not really enforced. More details here: https://www.tutorialsteacher.com/python/private-and-protected-access-modifiers-in-python

Everything not prefixed with one or two underscores is public.

In C, global variables and functions can be accessed from functions in other source files unless they are declared static. Not exactly the same as private, but C is not object-oriented so the concept of a class does not exist here.

Erich Kitzmueller
  • 36,381
  • 5
  • 80
  • 102
0

In python you can declare private members by putting dunders(double underscore) before member name, like this :

class Sample:
    def __init__(self):
        self.__private_mem = "Can be accessed only by member functions"
        self.public_mem = "Can be accessed as object properties outside the class"

sample = Sample()
print(sample.public_mem)
print(sample.__private_mem) # will raise an Error

But, I guess there is no such thing in C language as it is not object oriented.

  • 2
    1. The convention requires only one underscore. Names with double underscores are subject to name mangling. 2. It's only a convention that names with an underscore **should** be used privately. They are not technically declared private in any way. 3. Due to the name mangling the attribute will be `sample._Sample__private_mem`. – Klaus D. Oct 13 '20 at 07:53
  • Putting dunders before an attribute doesn't make it private, it just changes it's name to something that make it look like you really shouldn't touch it (name mangling). It's very similar to the C-way of making private members (https://stackoverflow.com/questions/2672015/hiding-members-in-a-c-struct). It's true that C is not object-oriented but you can make it work in a object-oriented way. – Lucas Charbonnier Oct 13 '20 at 07:59
  • @Klaus D. you can see here for private members and methods in python: https://www.geeksforgeeks.org/private-methods-in-python/ As far as C language is concerned so it is not based on OOP thus there is no such concept of classes. – Muhammad Hasham Oct 13 '20 at 09:18
  • You might want to read the article again. Quote: *"In Python, there is no existence of Private methods"* – Klaus D. Oct 13 '20 at 09:30
  • oh yes, I got it, Thanks!!! – Muhammad Hasham Oct 13 '20 at 17:55
  • You should update your answer. – Klaus D. Oct 14 '20 at 09:31