Given a class Mitarbeiter
with the constructor __init__
which is creating 3 variables. Can additional variables be added by another method in python? Example below:
class Mitarbeiter:
species = "Homo sapiens"
#Klassenmethoden ändern nur Klassenattribute
#statische Methoden verwenden werder Instanz- noch Klassenattribute
#konstruktor
def __init__ (self, vorname, name, personalnummer):
self.__vorname = vorname
self.__name = name
self.__personalnummer = personalnummer
def _def_abteilung(self, abteilung):
self.__abteilung = abteilung
def _set_vorgesetzter (self, vorgesetzter):
self.__vorgesetzer = vorgesetzter
@property
def get_abteilung(self,):
return self.__abteilung
when I create an Object of Mitarbeiter
with the variables vorname
, name
and personalnummer
I can call later the method _def_abteilung
to set some more information to the Object Mitarbeiter
.
ma1 = Mitarbeiter("Franz", "Bauer", 736) #--> Works
ma1._def_abteilung("Test") #--> Works
ma1.abteilung #--> does not work, any Ideas?
CodePudding user response:
The "
_name
is private" convention is a convention (privacy isn't enforced in any way),"
__name
" mangles the name soma1.__abteilung
literally doesn't exist outside the class.See What is the meaning of single and double underscore before an object name? and Python Name Mangling and How to Use Underscores
You can set attributes for an object anywhere -- if you changed self.__abteilung
to self.abteilung
, that name wouldn't be mangled by the interpreter and you would see the abteilung
attribute defined on all Mitarbeiter
objects.
Consider the following TestClass
example:
class TestClass:
def __init__(self, a):
self.a = a
def set_b(self, b):
self.b = b
def set_mangled(self, m):
self.__m = m
print("Mangled", self.__m)
def get_mangled(self):
return self.__m
- The
a
attribute is set in the__init__
, sot.a
always exists
t = TestClass(0)
print(t.a) # 0
print(t.b) # AttributeError
- The
b
attribute is only set in theset_b
method, so it only exists on an object after that method is called. The method can set an attribute of the object using the referenceself
. Trying to printt.b
before setting it throws anAttributeError
t.set_b(10)
print(t.a) # 0
print(t.b) # 10
print(t.c) # AttributeError
- The
c
attribute is set only once you run the linet.c = 100
. As you can see, it is possible to set the attribute from outside the class. Trying to accesst.c
before setting it throws an AttributeError.
t.c = 100
print(t.a) # 0
print(t.b) # 10
print(t.c) # 100
- The
__m
attribute is defined as a mangled name. Inside the class, it is accessed usingself.__m
. Outside the class, the name is mangled to_TestClass__m
, so it is not accessible ast.__m
ort.m
.
t.set_mangled(1000) # Mangled: 1000
print(t.get_mangled()) # 1000
print(t._TestClass__m) # 1000
print(t.__m) # AttributeError: 'TestClass' object has no attribute '__m'
print(t.m) # AttributeError: 'TestClass' object has no attribute 'm'