Understanding Python Classes

In general, a class represents a template, blueprint or type of language object and is primarily used in object-oriented (OO) languages such as Java or C++. Based on the class definition, you can create class instances. In Python, every object has a state (e.g. predefined data) and one or more methods to alter its state.

A simple example for a class is

class Beispiel: 
	""" Einfaches Beispiel """ 
	j = 1 

	def k(self): 
		return 'Hello' 
 
Obj = Beispiel() 
print(Obj.j) 
print(Obj.k) 

self here and in all further code snippets represents and references the instantiation of the class that is created. For example, def k(self) translates the method call Obj.k() to Beispiel.k(Obj). You don’t have to use self as representation of the object, some arbitrary name like OB or Identifier works the same. Using self is just a Python convention!

You may want to instantiate the Python class object obj with specific initial data, that is, a specific initial state the object possess when instantiated. For example, in the original class definition above every instance of the Beispiel class has the variable j with value 1. If you want to make the exact value of j dependent on the individual instantiation of the Beispiel class, you use the __init__() method as follows.

class Beispiel: 
	""" Einfaches Beispiel """ 
	def __init__(self, A, B, j): 
		self.data = []
                self.FirstLetter = A 
                self.SecondLetter = B
                self.j = j

	def k(self): 
		return 'Hello' 

Obj = Beispiel("H", "M", 2) 

Class attributes may also be declared after the class definition, e.g.

Obj.X = 4  
del Obj.X 

X was not part of the Beispiel class definition above but can be freely set as class attribute.

It is also possible to define a function outside of the class definition and then use or reference it inside it, also with the self input.

def k(self): 
	return 'Hello' 

class Beispiel: 
	""" Einfaches Beispiel """ 
	j = 1 

	k1 = k 

Finally, to create an empty class that can be filled up with data manually, use

class LeereKlasse: 
	pass 

Obj = LeereKlasse() 
Obj.Name = "NeuerName"