0

A newbie to oops concepts, so basically i know mostly general oops concepts. but trying a lot to make a variable inside a class public private and protected. I know that they are done using 1 & 2 underscores with a variable name. How do u initialise acess modifiers, call them set a value to them ? Basically i'm looking for a general example/syntax.

also i have been reading a lot about python. but i have never found something related to doc can somebody please give me a overview as to how this works as well.

Thanks a ton

2 Answers2

0

Python has no concept of a private field or method. However, identifiers that begin with two underscores, but do not end with two underscores, will be "mangled" with the class name to prevent accidental overrides. You can find more information here.

That's a part of the language. It's conventional as a programming practice that identifiers beginning with single underscores should be considered private. That's a polite request that is not enforced...but it's a Real Good Idea to leave single-underscore names along.

The other underscore convention that I'm aware of is that a name consisting of a single underscore is often used in a for loop, list comprehension or generator expression when the control variable is not going to be used in the loop. For example, Doing something n times might look like:

for _ in range(n):
    ...statements to repeat
Community
  • 1
  • 1
Mike Housky
  • 3,959
  • 1
  • 17
  • 31
0

Python does not have private variables, starting an attribute with an underscore (_) is a way of indicating it is private to other programmers, see here for more details.

Since there are no private variables ones starting with an underscore can be modified like any other.

class MyClass():
     """Docstrings are important"""
     def __init__(self):
         self._myPrivateNumber = 42


C = MyClass()
C._myPrivateNumber #42
C._myPrivateNumber = 1
C._myPrivateNumber #1
setattr(C, '_myPrivateNumber', -1)
C._myPrivateNumber #-1

I am assuming you also want to know about __doc__. It is called a docstring and is used to document your objects. It is created from the string immediately after the declaration, e.g. the doc string of C, C.__doc__ is the string "Docstrings are important" You can read about how it is created here. If a docstring is not provide __doc__ will be ''. They are also used to crete the help information i.e. help(C) will use the docstring.