简体   繁体   English

在Python中实例化类时出错

[英]Error instantiating a class in Python

I'm attempting to instantiate a class: 我正在尝试实例化一个类:

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)

but buyer = Customer(name, money, ownership) keeps getting errored: 但是buyer = Customer(name, money, ownership)不断出错:

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

But I thought I set the variable's values in my dictionary with "Customer(...)" 但是我以为我在字典中使用“ Customer(...)”设置了变量的值

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) 

Solution for your mentioned problem is above, you just need to define some values. 上面提到的问题的解决方案,您只需要定义一些值即可。 But there are some other issues as well, like bikes.values(), from where this came? 但是还有其他一些问题,例如bikes.values(),这是从哪里来的呢?

Remember, to use something, you have to first tell what it is, so define things. 记住,要使用某种东西,您必须首先说出它是什么,然后定义一下东西。

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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