0

I'm following a youtube tutorial on doing OOP, and in this tutorial, he said that you can indicate which data type you can pass in a parameter by using var: datatype (i.e Name: str). And then he showed the error message when you try to input something that is not a str type. But when I try to do it, my program still runs without any error?

class Item:
  def __init__ (self, name, price: str , quantity):
    self.name = name
    self.price = price
    self.quantity = quantity
  
  def calculate_total_price(self):
    return self.price * self.quantity

item1 = Item("Phone",10,20)

print(item1.calculate_total_price())

OUTPUT:

200

In the code above, I made the price parameter only take in str data types, but when I try to run it, it still runs without any error?

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
TheShin
  • 77
  • 5
  • 2
    Type annotations don't enforce type safety. Quote from the [Docs](https://docs.python.org/3/library/typing.html): *The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc.* – Ch3steR Dec 20 '21 at 06:14
  • 1
    "And then he showed the error message when you try to input something that is not a str type" No, they did not show that unless they *explicitly added code themselves that checks the type*. Python type hints are never enforced at runtime, unless you write code that does (or use a library, like `pydantic`, that does that for you). – juanpa.arrivillaga Dec 20 '21 at 06:55

0 Answers0