Aktuell bin ich beim Thema Objektorierntierung
Klassen, Methoden
Und hier bei der Komposition.
Ich brauche das nicht erklären, wisst ihr besser.
Hier habe ich nun eine kleine Frage. Ich habe zwei Code Beispiele für Komposition.
Code 1 aus dem Internet
Code 2 aus einem Buch, das ich neben meinem Udemy Kurs lese.
Code 1
Code: Alles auswählen
class Employee:
def __init__(self, name, age):
self.name = name
self.age = age
def emp_data(self):
print('Name of Employee : ', self.name)
print('Age of Employee : ', self.age)
class Data:
def __init__(self, address, salary, emp_obj):
self.address = address
self.salary = salary
self.emp_obj = emp_obj
def display(self):
self.emp_obj.emp_data()
print('Address of Employee : ', self.address)
print('Salary of Employee : ', self.salary)
emp = Employee('Ronil', 20)
data = Data('Indore', 25000, emp)
data.display()
self.emp_obj.emp_data() emp_obj von data ist emp_obj und das ist emp
Also ist der code = emp.emp_data()
emp_data ist eine Klasse davor und definitert und wird durch emp = Employee('Ronil', 20)
Im Konstruktor gebildet.
Soweit alles klar hier auch wie Data konstruiert wird.
Nun Code 2:
Code: Alles auswählen
class WindowsMyDocuments:
def save(self,document):
destination = Path.home() / "Documents" / "scan.txt"
print("Saving to: ", destination)
destination.write_text(document)
class LinuxHomeDir:
def save(self,document):
destination = Path.home() / "scan.txt"
print("Saving to: ", destination)
destination.write_text(document)
class Fileprinter:
def __init__(self, windows, linux):
self._windows = windows
self._linux = linux
def print(self, document):
destination =(
self._linux
if platform.system() = "linux"
else self._windows
)
destination.save(document)
print_to_file = Fileprinter(
windows = WindowsMyDocumemts(),
linux = LinuxHomeDir()
)
print_to_file.print(file1)
print_to_file = Fileprinter(
windows = WindowsMyDocumemts(),
linux = LinuxHomeDir()
)
Das windows=WindowsMy…… ist doch nicht nötig oder?
Es geht doch auch wie in Code1:
print_to_file = Fileprinter(
WindowsMyDocumemts(),
LinuxHomeDir()
)
Oder irre ich mich?