简体   繁体   中英

Create a inherited class with user input

I'm trying to code a product inventory project. I stumbled across this problem and have been searching since a few days but couldn't find any way to do it. How can I create a class inherited from the base class with user input..

Here is the base class:

class Product:
    def __init__(self, title, color, price):
        self.title = title
        self.color = color
        self.price = price

what I'm trying to achive is that user will be able to add products himself by lets say pressing 2 will ask him to enter the product type (coat) and than the parameters specific to the product which will create a new class inherited from the base class. Like this:

class coats(Product):
    def __init__(self, material, size):
    self.material = material
    self.size = size

I can create instances with user input but creating inherited classes I couldn't figure it out. I appreciate if you could help. Thanks.

While you can generate classes dynamically with the type() function , you really do not want to do this here. Code generation to model user-generated data only leads to very, very difficult to manage code that looks up attributes and variable names dynamically.

Use a datastructure in your existing class to store user-generated data. All you need is a dictionary:

class Product:
    def __init__(self, type, price, properties):
        self.type = type
        self.price = price
        self.properties = properties

then to create a coat product use:

products = {}
products['coat'] = Product('coat', 10.0, {'color': 'some color', 'material': 'some material', size: 12})

where the various values, and the key in products are not literals but variables with user input.

Classes model your application, and contain the data. Don't create separate models for the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM