在Python中将值从一个类传递到另一个类

时间:2017-04-30 01:36:57

标签: python oop

我在Python上发布OOP,但有一个例外,我有以下内容:

class Burrito:
    def __init__(self, meat):
        self.meat = self.set_meat(meat)

    def set_meat(self, meat):
        self.meat = ["chicken", "pork", "steak", "tofu"]
        if meat in self.meat:
          self.meat = meat
        else:
          self.meat = False
        return self.meat

    def get_meat(self):
        return self.meat

    def get_cost(self, cost = 25):

        if self.meat in self.meat:
          return cost
        else:
          return 0


newBurrito = Burrito("steak")
print(newBurrito.get_cost())

这个练习的目标是检查墨西哥卷饼(肉)是否是“牛排”,如果是,则值为25。

现在我被赋予了另一个名为Meat的类,我必须重写代码来做同样的事情而且我不能改变类Meat 只有Burrito类,这是代码我:

class Meat:
    def __init__(self, value=False):
        self.set_value(value)

    def get_value(self):
        return self.value

    def set_value(self, value):
        if value in ["chicken", "pork", "steak", "tofu"]:
            self.value = value
        else:
            self.value = False

class Burrito:
    def __init__(self, meat):
        self.meat = Meat(meat)

    def get_cost(self, cost = 25):
        if self.meat in self.meat:
          return cost
        else:
          return 0


newBurrito = Burrito("steak")
print(newBurrito.get_cost())

正如您在费用方法中所看到的,我不知道如何将价值从Class Meat传递给Class Burrito,您能帮助我吗?

2 个答案:

答案 0 :(得分:0)

def get_cost(self, cost = 25):
    if self.meat.get_value() == "steak":
      return cost
    else:
      return 0

答案 1 :(得分:0)

class Meat:
    def __init__(self, value=False):
        self.set_value(value)

    def get_value(self):
        return self.value

    def set_value(self, value):
        if value in ["chicken", "pork", "steak", "tofu"]:
            self.value = value
        else:
            self.value = False


class Burrito:
    def __init__(self, meat):
        self.meat = Meat(meat)

    def get_cost(self, cost = 25):
        if self.meat:
            return cost


newBurrito = Burrito("steak")
print(newBurrito.get_cost())

I have slightly changed your codes. When you use Meat(meat) in init function, Meat(meat) construct an object in which meat.value is the result. What you need to do is to simply judge if it is True.