python: specify class argument type

Question:

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'>
Asked By: Abel Gutiérrez

||

Answers:

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)
Answered By: korzck
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.