Home > Enterprise >  How to automatically create a new class variable when you call the same class everytime
How to automatically create a new class variable when you call the same class everytime

Time:11-12

I want book1 to be created automatically without defining it, because this will be a while code so what I want to achieve is every time a user fill these inputs it creates book1 then book2, etc. and most importantly a way I can call them again

class Book(object): #this class stores books in detail
    def __init__(self, title: str , author: str, isbn: int, genre: str, numCopies: int):
        self._title: str = title
        self._author: str = author
        self._isbn: int = isbn
        self._genre: str = genre
        self._numCopies: int = numCopies



title = input("The Book's Title: ")
author = input("The Book's Author: ")
isbn = int(input("The Book's ISBN: "))
genre = input("The Book's Title: ")
numCopies = int(input("The Book's Copies: "))

book1 = Book(title,author,isbn,genre,numCopies)

CodePudding user response:

Generally when you have repetitive code, you can write a function for that.

This can be done in many ways. One of them is using a classmethod as another constructor for your class:

class Book:  # this class stores books in detail
    def __init__(self, title: str, author: str, isbn: int, genre: str, numCopies: int):
        self._title = title
        self._author = author
        self._isbn = isbn
        self._genre = genre
        self._numCopies = numCopies

    @classmethod
    def from_user_input(cls):
        title = input("The Book's Title: ")
        author = input("The Book's Author: ")
        isbn = int(input("The Book's ISBN: "))
        genre = input("The Book's Title: ")
        numCopies = int(input("The Book's Copies: "))
        return cls(title, author, isbn, genre, numCopies)


book1 = Book.from_user_input()

You can then append the instances to a list/dictionary named Books for example.

Note-1: You don't need to inherit from object in Python 3.

Note-2: If you just created this class to hold data, take a look at namedtuple. It is much more lightweight.

Note-3: Although it's possible to type annotate variables inside your __init__, its useless in your case. For example self._title gets the value of title from parameters and you already defined str for that there. Its an unnecessary duplication. Static type-checkers can hint you from parameter itself.

  • Related