简体   繁体   中英

calling a class function python

class merchandise:
    def __init__(self, item, quantity, cost):
        self.__item = item
        self.__quantity = quantity
        self.__cost = cost
    def set_item(self, item):
        self.__item = item
    def set_quantity(self, quantity):
        self.__quantity = quantity
    def set_cost(self, cost):
        self.__cost = cost
    def get_item(self):
        return self.__item
    def get_quantity(self):
        return self.__quantity
    def get_cost(self):
        return self.__cost
    def get_inventory_value(self):
        return (format(self.__quantity * self.__cost, '.2f'))
    def __str__(self):
        for i in merchandise:
            print (self.__item+',', self.__quantity,'@ $'+(format (self.__cost,'.2f')))

import merchandise
def main(_):
    def make_list():
        for count in range (1,3):

            merchandise.set_item("hammer")
            merchandise.set_quantity(10)
            merchandise.set_cost(14.95) 
            print(hammer)

            hardware = float (input ('Enter a new quantity for hardware '))
            jewelry = float (input ('Enter a new cost for jewelry '))
            hammer = merchandise.merchandise()

    stuff = make_list()
    print (stuff)
main()

I don't know what I am doing wrong I get there error there is no set_item in merchandise. I have tried quite a few things and nothing has worked so far. Am I way off here or is it something stupid.

The error isn't that there's no set_item ; the error is caused by the fact that you haven't initialized and as a result the required positional argument self isn't implicitly passed.

When invoking functions class instances, they become bound methods on that instance and the instance is always (except if decorated) implicitly passed as the first argument.

In short, initialize a mechanize instance and then invoke the functions, ie:

m = merchandise('', 10, 0.0) 
m.set_item("hammer")
m.set_quantity(10)
m.set_cost(14.95) 

Note that setting isn't required, you can provide these during initialization:

m = merchandise('hammer', 10, 14.95) 

Also, you can't import in the module you're defining (if that is what you're doing), it will raise an error normally. If it is in different modules make sure you import the actual class too:

from merchandise import merchandise

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