Klassenaufruf per String
Verfasst: Donnerstag 3. August 2023, 16:20
Ich habe eine Klasse "Laptop" erstellt, die sich in einem separaten Modul befindet. Inzwischen existieren 26 Instanzen, die ich folgendermaßen ausgeben kann:
laptop1.details()
laptop2.details()
usw.
Um nicht alle Instanzen einzeln aufrufen zu müssen, habe ich eine Schleifenkonstruktion probiert, die nicht funktioniert. Hier nun der Code:
import sys, os
current = os.path.dirname(os.path.realpath(__file__))
parent = os.path.dirname(current)
sys.path.append(parent)
from utils.classlib import Laptop
laptop1 = Laptop('HP1','AMD 64',5,16,700)
laptop2 = Laptop('HP2','AMD 64',5,16,700)
laptop1.details()
laptop2.details()
for i in range(1,3):
res = ""
res = "laptop"+str(i)+".details()"
print(res)
Und hier jetzt die Ausgabe:
The details of the laptop are:
Name : HP1
Processor : AMD 64
HDD Capacity : 5
RAM : 16
Cost : 700
The details of the laptop are:
Name : HP2
Processor : AMD 64
HDD Capacity : 5
RAM : 16
Cost : 700
laptop1.details()
laptop2.details()
Könnte mir jemand eine Tipp geben, wie das Problem gelöst werden kann?
Vielen herzlichen Dank.
Fredo
laptop1.details()
laptop2.details()
usw.
Um nicht alle Instanzen einzeln aufrufen zu müssen, habe ich eine Schleifenkonstruktion probiert, die nicht funktioniert. Hier nun der Code:
import sys, os
current = os.path.dirname(os.path.realpath(__file__))
parent = os.path.dirname(current)
sys.path.append(parent)
from utils.classlib import Laptop
laptop1 = Laptop('HP1','AMD 64',5,16,700)
laptop2 = Laptop('HP2','AMD 64',5,16,700)
laptop1.details()
laptop2.details()
for i in range(1,3):
res = ""
res = "laptop"+str(i)+".details()"
print(res)
Und hier jetzt die Ausgabe:
The details of the laptop are:
Name : HP1
Processor : AMD 64
HDD Capacity : 5
RAM : 16
Cost : 700
The details of the laptop are:
Name : HP2
Processor : AMD 64
HDD Capacity : 5
RAM : 16
Cost : 700
laptop1.details()
laptop2.details()
Könnte mir jemand eine Tipp geben, wie das Problem gelöst werden kann?
Vielen herzlichen Dank.
Fredo