Home > OS >  Adding variables to a class
Adding variables to a class

Time:12-13

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:

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__, so t.a always exists
t = TestClass(0)
print(t.a) # 0
print(t.b) # AttributeError
  • The b attribute is only set in the set_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 reference self. Trying to print t.b before setting it throws an AttributeError
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 line t.c = 100. As you can see, it is possible to set the attribute from outside the class. Trying to access t.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 using self.__m. Outside the class, the name is mangled to _TestClass__m, so it is not accessible as t.__m or t.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'
  • Related