Home > Mobile >  python: specify class argument type
python: specify class argument type

Time:09-04

I have this class:

class Transaction:
    
    def __init__(self, date, value, concept : str = ""):
        self.date = date
        self.value =value
        self.concept = concept

if __name__ == "__main__":
    
    transaction = Transaction(date=1,value=1,concept=1)
    print(transaction)
    print(type(transaction.concept))

I want Transaction.concept to be a str, but as you can see below, it accepts 1:

<__main__.Transaction object at 0x0000023AEAB88BE0>
<class 'int'>

CodePudding user response:

This question can help you understand python typing. Quote from this link:

Python does not have variables, like other languages where variables have a type and a value; it has names pointing to objects, which know their type.

So, if you will run

def func(arg: str):
    print(type(arg))
func(1)

You will get

<class 'int'>

My suggestion for your code it to use explicit type conversion

class Transaction:
    def __init__(self, date, value, concept : str = ""):
        self.date = date
        self.value = value
        self.concept = str(concept)
  • Related