1

I would like to create a class in Python. Is it possible to specify the type of argument given in init ? Otherwise raise an error or smth like this ?

I would like to create this type of class : where ligne_225 is a list data is a dataframe

class Poste_HTB_HTA:
  def __init__(self, ligne_225,data):
    self.ligne_225 = ligne_225

    self.data = data


  def ligne_225(self):
    return self.ligne_225
Thomas LESIEUR
  • 408
  • 4
  • 14

2 Answers2

0

You can do as follows:

class Poste_HTB_HTA:
  def __init__(self, ligne_225: list, data: pandas.dataframe):
    if not isinstance(ligne_225, list): #Checks if ligne_225 is a instance of list
        raise TypeError("ligne_225 must be of type 'list'")
    if not isinstance(data, pandas.dataframe): #Checks if data is a instance of dataframe
        raise TypeError("data must be of type 'dataframe'")
    
    self.ligne_225 = ligne_225
    self.data = data


  def ligne_225(self):
    return self.ligne_225
Alex Waygood
  • 6,304
  • 3
  • 24
  • 46
0

something like the below

from typing import Dict


class Poste_HTB_HTA:
    def __init__(self, ligne_225: int, data: Dict) -> None:
        if not isinstance(ligne_225, int):
            raise ValueError(f'{ligne_225} must be int')
        self.ligne_225 = ligne_225
        self.data = data

    def ligne_225(self) -> int:
        return self.ligne_225

balderman
  • 22,927
  • 7
  • 34
  • 52