Search code examples
pythonooppython-class

Python OOP datatype


Why does it say 'Die eingegebenen Daten haben den falschen Datentyp!' when the datatypes are actually right? Doesn't even work with just matrNr... Although I checked my input of matrNr to be an int?!

class Student:
    def __init__(self):
        self.matrNr = -1
        self.vorname = ''
        self.nachname = ''
        self.gebDatum = []
        self.email = ''
        self.telNr = ''

    def DatenUebergeben(self, matrNr, vorname, nachname, gebDatum, telNr):  
        if matrNr == int and vorname == str and nachname == str and gebDatum == list and telNr == str:
            print('richtige Datentypen!')
        else:
            print('Die eingegebenen Daten haben den falschen Datentyp!')

student1 = Student()
student1.DatenUebergeben(12345,'linda','f',[2,2,1995],'12345')

Solution

  • Background

    By checking (for example) matrNr == int you actually compare the variable matNr, which is an int (an instance of <class 'int'>) to the class int (<class 'int'>).

    Quick fix

    You can use the type()-function to get the type of a variable, resulting in type(matrNr) == int. This does exactly what you are trying to achieve.

    Better solution

    In Python you can define the types of variables a function accepts by adding : <type> after the argument. The better solution would thus be:

    def DatenUebergeben(self, matrNr: int, vorname: str, nachname: str, gebDatum: list, telNr: str):
        # do something