Encapsulation; die gekapselten Werte können weder abgerufen noch verändert werden, wenn Sie sie ausschließlich verwenden möchten.
Ein Name, der mit zwei Unterstrichen (__) beginnt, wird privat – er ist von außen nicht sichtbar. So implementiert Python das Kapselungskonzept.
class Iamclass:
def init(self):
self.i_am_private = [1, 2, 3]
new_object = Iamclass()
print(len(new_object.i_am_private))
—> 3
class Iamclass:
def init(self):
self.__i_am_private = [1, 2, 3]
new_object = Iamclass()
print(len(new_object.__i_am_private))
–> AttributeError: ‚Iamclass‘ object has no attribute ‚__i_am_private‘
Superclass, Encapsulation, Inheritance
class MySuperClass:
def __init__(self):
self.__stk = [] # with __ you make stk private - encapsulation
def put_it(self, val):
self.__stk.append(val)
def take_out(self):
val = self.__stk[-1]
del self.__stk[-1]
return val
class MySubClass(MySuperClass): # Inheritance
def __init__(self):
MySuperClass.__init__(self) # initializing MySuperClass in the MySUbClass
self.counter = 0 # new attribute belonging to MySUbClass
def get_count(self): # self is pointing to the current class
return self.counter
def take_out(self): # define the method from the Superclass with extra features
MySuperClass.take_out(self) # call the method from the Superclass
self.counter += 1 # extra feature
def isempty(self):
if len(self.some_attribute_from_sub_or_super) == 0:
return True
else:
return False
# Run the program
i_am_a_class_instance = MySubClass() # creating a class i.e. initializing it
for i in range(100):
i_am_a_class_instance.put_it(i)
i_am_a_class_instance.take_out()
print(i_am_a_class_instance.get_count())
vordefinierter Eigenschaften und Methoden
Sie können dem Objekt Eigenschaften außerhalb der Klasse zuweisen, d. h. ClassInstance.NEW_PROPERTY = 5
Python-Objekte werden bei der Erstellung mit einem kleinen Satz vordefinierter Eigenschaften und Methoden ausgestattet.
__dict__ ist eine Variable, die die Namen und Werte aller Eigenschaften (Variablen) des Objekts enthält
Instance variables
- Definition: Attributes that belong to a specific object (instance) of a class.
- Existence: They live inside the object’s memory.
- If you never create an object of the class, there’s nowhere for those attributes to live—so they don’t exist.
Class variables
- Definition: Attributes that belong to the class itself and are shared by all its instances.
- Existence: Stored on the class object, which Python creates as soon as the
class
statement is executed.- Therefore, a class variable “exists in one copy” even before you make any instances.
Class Variables + counting Object Instantiations
class ClassVariableExample:
class_var = 0
def __init__(self, n = 1):
self.__first = n
ClassVariableExample.class_var += 1
example_1 = ClassVariableExample()
example_2 = ClassVariableExample(2)
example_3 = ClassVariableExample(4)
print(example_1.__dict__)
print(ClassVariableExample.__dict__)
{'_ClassVariableExample__first': 1} 3
{'_ClassVariableExample__first': 2} 3
{'_ClassVariableExample__first': 4} 3
class_var ist eine Klassenvariable. Sie erhöht sich im Konstruktor jedes Mal um +1, wenn ein neues Objekt dieser Klasse erstellt wird. Der Wert der Klassenvariable ist für alle Objekte dieser Klasse gleich.
hasattr(objectName, attrName)
Prüft, ob ein Objekt ein Attribut hat.
hasattr(Object, attribute) -> True or False
hasattr(ClassCode, attribute) -> True or False
__init__ , __dict__ , __name__ , __module__ , __bases__
__init__ – Dies ist die Konstruktormethode in Python. Sie wird implizit aufgerufen, wenn ein Objekt erstellt wird.
print(object_instance.__dict__)
print(Class_Name.__dict__)
__name__ – enthält den Namen der Klasse, zu der das Objekt gehört
print(ClassName.__name__)
object1 = ClassName()
print(type(object1 ).__name__)
__module__ – enthält als Wert den Namen des Moduls, das die Definition der Klasse enthält
__bases__ – nur Klassen haben dieses Attribut – Objekte nicht. Ergibt ein Tupel, das Klassen enthält, die direkte Superklassen für die Klasse sind.
Instanzvariable vs. Klassenvariable
Eine Klassenvariable ist eine Eigenschaft, die in genau einer Kopie existiert und für deren Zugriff kein erstelltes Objekt erforderlich ist. Solche Variablen werden nicht als dict-Inhalt angezeigt.
Eine Instanzvariable ist eine Eigenschaft, deren Existenz von der Erstellung eines Objekts abhängt. Jedes Objekt kann einen anderen Satz von Instanzvariablen haben.
__method_name
__method ist eine versteckte Methode und kann aufgerufen werden als objectName._ClassName__method
Introspektion und Reflexion
Introspektion – Analyse und Entdeckung
Reflexion – Manipulation