Home > Mobile >  Python set variables types inside class
Python set variables types inside class

Time:11-13

I am trying to set acceptable built-in types for my class variables. I want to throw an exception if given type is incorrect. Is there any better way than setter with isinstance()?

My first attempt:

class Address:
    city: str
    building_number: str or int
    apartment_number: int
    street: str

    def __init__(self, city, building_number, apartment_number, street):
        self.city = city
        self.building_number = building_number
        self.apartment_number = apartment_number
        self.street = street

Unfortuantely it compiles regardless of type.

My second attempt:

class Address:
    def __init__(self, city: str, building_number: str, apartment_number: int, street: str):
        self.city = city
        self.building_number = building_number
        self.apartment_number = apartment_number
        self.street = street

This one actually shows the wrong type when creating a class but it compiles without throwing any error or message.

enter image description here

enter image description here

CodePudding user response:

isinstance() is a safe way, but if you want just to type less, you may use the type checking that is done by " " operator like below

class Address:
    city: str
    building_number: str or int
    apartment_number: int
    street: str

    def __init__(self, city:str, building_number:str, apartment_number:int, street:str):
        self.city = ""   city
        self.building_number = ""   building_number
        self.apartment_number = 0   apartment_number
        self.street = ""   street

x = Address(1, "a", "b", "c")

And the stacktrace message is meaningful:

Traceback (most recent call last):
  File "test.py", line 14, in <module>
    x = Address(1, "a", "b", "c")
  File "test.py", line 9, in __init__
    self.city = ""   city
TypeError: must be str, not int

CodePudding user response:

I tried this and I get no an error:

class Address:
    def __init__(self, city: str, building_number: str, apartment_number: int, street: str):
        self.city = city
        self.building_number = building_number
        self.apartment_number = apartment_number
        self.street = street

a = Address(1, "asassa", "shoudbeanint", "asas")

print (a.city)
print (a.apartment_number)
  • Related