0

I want to know that are dunder attributes or special attributes private (not accessible outside the class)? Are dunder methods also private? If yes, then check my code comments below:

class Employee():
    def __init__(self,name,age,salary,pin):
        self.name=name
        self.age=age
        self.__salary=salary
        self.__pin=pin
    def __str__(self):
        return f"{self.name} {self.age}"

obj1=Employee("Ali",45,"454543",234)
print(obj1.__dict__) # Is it a good practice to use __dict__(special attribute) outside the class? as they are private
print(obj1.__str__()) # Is it a good practice to use __str__ (dunder method) outside the class? as they are private
MattDMo
  • 100,794
  • 21
  • 241
  • 231
  • 1
    They are accessible, as you demonstrate. Typically, these dunder methods are invoked by some other operation, e.g. `str(x)` performs `x.__str__()`, so typically you don't use the dunder methods directly. Note that `self.__salary` becomes `obj1.__Employee_salary`, so you can use that name outside of the class, too. – a_guest Aug 22 '22 at 13:18
  • 1
    @a_guest `self.__salary` actually becomes `obj1._Employee__salary`. – MattDMo Aug 22 '22 at 13:20
  • @a_guest what about __dict__ attribute using outside the class? – Ali Murtaza Aug 22 '22 at 13:20
  • @AliMurtaza Why would you want to do that? What problem are you actually trying to solve? – a_guest Aug 22 '22 at 13:28
  • @a_guest just for understanding... – Ali Murtaza Aug 22 '22 at 13:31
  • @AliMurtaza What do you want to understand? You can do it, as you demonstrated. But typically you'd access the attributes directly. – a_guest Aug 22 '22 at 13:41
  • The important thing to understand is that *Python doesn't have private attributes*. – juanpa.arrivillaga Aug 22 '22 at 13:47

0 Answers0