python 3 - instantiating class from user input

Chris Rebert clp2 at rebertia.com
Thu Apr 7 00:53:37 EDT 2011


On Wed, Apr 6, 2011 at 9:41 PM, Chris Rebert <clp2 at rebertia.com> wrote:
> 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:

I forgot; third, particularly hackish, variant, included solely for
the sake of completeness:

class InventoryItem:
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)

This requires that the caller use keyword arguments, and doesn't check
at all whether the correct arguments were supplied.
Generally, I would not recommend use of this hack.

Cheers,
Chris



More information about the Python-list mailing list