Python Forum
Author class, with constructor validations
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Author class, with constructor validations
#1
class Author:

    def __init__(self, id, firstname, lastname):
        self._validateid(id, "ID")
        self._validate_author(firstname, "First Name")
        self._validate_author(lastname, "Last Name")

        self._id = id
        self._firstname = firstname
        self._lastname = lastname

    def _validateid(self, id, error_message):
        if id < 1:
            raise ValueError(error_message + " is invalid")

    def _validate_author(self, parameter, error_message):
        if not parameter:
            raise TypeError(error_message + " is missing")

    @property
    def iden(self):
        return self._id

    @property
    def first_name(self):
        return self._firstname

    @property
    def last_name(self):
        return self._lastname
I created an Author class and wanted to ensure that all the parameters were valid during construction. I created a private method to validate the parameters, and if it's invalid or missing, it raises an error. Is this okay? What is the Python way of doing it?
Reply


Messages In This Thread
Author class, with constructor validations - by nexusfactor - Oct-12-2017, 09:57 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Why doesn't calling a parent constructor work with arbitrary keyword arguments? PurposefulCoder 4 981 Jun-24-2023, 02:14 PM
Last Post: deanhystad
  Not including a constructor __init__ in the class definition... bytecrunch 3 12,072 Sep-02-2021, 04:40 AM
Last Post: deanhystad
  syntaxerror when entering a constructor MaartenRo 2 2,013 Aug-03-2020, 02:09 PM
Last Post: MaartenRo
  error in constructor overriding in python3 srm 1 1,836 Jul-18-2019, 12:21 PM
Last Post: ichabod801
  This constructor takes no arguments Friend 2 5,363 Jun-26-2019, 02:54 PM
Last Post: Friend
  class constructor with dataframe UGuntupalli 2 2,347 Jun-11-2019, 10:50 PM
Last Post: UGuntupalli
  Overload of constructor psosmol 2 2,828 Apr-17-2019, 05:10 AM
Last Post: psosmol
  Constructor Rajesh1978 2 3,228 May-22-2018, 05:18 PM
Last Post: micseydel
  I'm trying to make a constructor without hardcoding all of the values RedSkeleton007 7 4,523 Apr-05-2018, 11:12 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020