python 3 - instantiating class from user input

Chris Rebert clp2 at rebertia.com
Thu Apr 7 06:41:39 CEST 2011


On Wed, Apr 6, 2011 at 9:04 PM, Brad Bailey <computer_brad at yahoo.com> wrote:
> I dont understand why this is such a big deal. Nor do i understand why google can't find a reasonable answer. If one can't figure out from the title what I'm trying to do, then a look at code should firmly plant the intent. The general idea of the code is, in my opinion, very basic.
>
> I notice, that when you are coding a class instance, it's in the format of:
> newInstance = someClass()
>
> OK, so we are calling someClass as if it's a function. Is there a way to do something to the effect of:
>  someClass(newInstance)

I fail to understand what that line of code is supposed to accomplish
or how it relates to your titular question.

> I've seen all kinds of hacks and workarounds that seem 10 times more complicated that this ought to be.
>
> class inventoryItem:
>    itsDecrtiption = None
>    itsVendor = None
>    itsCost = None
>    itsMarkup = None
>    itsQuantity = None

That's defining class variables (Java lingo: "static" variables),
*not* instance variables. You want:

class InventoryItem:
    def __init__(self, description, vendor, cost, markup, quantity):
        self.description = description
        self.vendor = vendor
        self.cost = cost
        self.markup = markup
        self.quantity = quantity

Or using collections.namedtuple:

from collections import namedtuple
InventoryItem = namedtuple('InventoryItem', "description vendor cost
markup quantity".split())
# See http://docs.python.org/library/collections.html#collections.namedtuple


You would make a new instance of InventoryItem based on console user
input like so (ignoring input validation / error checking):

desc = input("Description: ")
vend = input("Vendor: ")
c = float(input("Cost: "))
m = float(input("Markup: "))
qty = int(input("Quantity: "))
newItem = InventoryItem(desc, vend, c, m, qty)

Exploiting dynamism can eliminate most of the redundancy, at the cost
of simplicity:

def identity(x): return x
fields = "description vendor cost markup quantity".split()
converters = [identity, identity, float, float, int]
newItem = InventoryItem(*[converter(input(field.title()+": ")) for
field, converter in zip(fields, converters)])

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list