【问题标题】:Error instantiating a class in Python在 Python 中实例化类时出错
【发布时间】:2015-04-01 15:47:38
【问题描述】:

我正在尝试实例化一个类:

class Customer(object):
    def __init__(self, name, money, ownership):
        self.name = name
        self.money = money
        self.ownership = ownership

    def can_afford(self):
        x = False
        for bike in bikes.values():

            if self.money >= bike.money * margin:
                print "Customer {} can afford {}".format(self.name, bike)
                x = True
        if not x:
            print "Customer {} cannot afford any bikes at this time.".format(self.name)

shoppers = {        
    # Initial condition of shopper1
    "Jane": Customer("Jane", 200, False),
    # Initial condition of shopper2
    "Alfred": Customer("Alfred", 500, False),
    # Initial condition of shopper3
    "Taylor": Customer("Taylor", 1000, False)
}

buyer = Customer(name, money, ownership)

buyer = Customer(name, money, ownership) 不断出错:

Undefined variable 'name'
Undefined variable 'money'
Undefined variable 'ownership'

但我认为我在字典中使用“Customer(...)”设置变量的值

【问题讨论】:

  • 是的,您已经为 Jane、Alfred 和 Taylor 奠定了基础。那个单独的“买家”实例化是什么?它的值应该来自哪里?

标签: python function class dictionary instantiation


【解决方案1】:
class Customer(object):
    def __init__(self, name, money, ownership):
        self.name = name
        self.money = money
        self.ownership = ownership

    def can_afford(self):
        x = False
        for bike in bikes.values():

            if self.money >= bike.money * margin:
                print "Customer {} can afford {}".format(self.name, bike)
                x = True
        if not x:
            print "Customer {} cannot afford any bikes at this time.".format(self.name)

shoppers = {        
    # Initial condition of shopper1
    "Jane": Customer("Jane", 200, False),
    # Initial condition of shopper2
    "Alfred": Customer("Alfred", 500, False),
    # Initial condition of shopper3
    "Taylor": Customer("Taylor", 1000, False)
}
#this is solution for your MENTIONED problem only
name = 'Buddy' 
money = 2
ownership = 'something'
buyer = Customer(name, money, ownership) 

上面提到的问题的解决方案,您只需要定义一些值。 但是还有其他一些问题,比如bikes.values(),这是从哪里来的?

记住,要使用某个东西,你必须先说明它是什么,然后定义它。

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2015-10-18
    • 1970-01-01
    • 2015-01-02
    • 2015-02-25
    • 1970-01-01
    • 2015-04-30
    • 2016-06-01
    • 2021-08-24
    • 1970-01-01
    相关资源
    最近更新 更多