jonahxuworld 2023-02-18 00:07 采纳率: 93.1%
浏览 29
已结题

关于#python#出现的问题,如何解决?

求解决以下python出现的问题,要做出如何修改才能运行成功呢?
下面是我的代码和错误信息:

# 1. Implement a class named "MyClass"
# This class should have:
# * During instantiation of this class, the 'some_val' parameter should be set as
#   a variable with the same name in the instance
# * Implement the method called 'plus_n' that takes one parameter (named 'n'), such that
#   it should return the sum of instance's 'some_val' variable and 'n'
class MyClass:
    def __init__(self, some_val):
        self.some_val = some_val

    def plus_n(self, n):
        return self.some_val + n

#####################################################################################################################
#####################################################################################################################

# 2. Given two classes 'Animal' and 'DigestiveSystem, implement, using COMPOSITION the method 'eat_food' in the 'Animal' class.
# * Animal instances should have a 'diggestive_system' attribute, which is the DigestiveSystem instance of that object.
# * The eat_food method should PROCESS any 'food' (any string) that are not allergenic (use the method 'has_allergy' to check for this case)
# * The DigestiveSystem is a class responsible for the PROCESS of any food eaten,
#       so make use of this in the Animal.eat_food method (remember COMPOSITION!)

class DigestiveSystem:
    """This class is already done for you
    don't changea any code on it.
    """
    def process_food(self, food):
        return f'processed-{food}'


class Animal:
    def __init__(self):
        self.digestive_system = DigestiveSystem()

    def has_allergy(self, food):
        if food.lower() in ['peanut', 'milk']:
            return True
        return False

    def eat_food(self, food):
        if not self.has_allergy(food):
            return self.digestive_system.process_food(food)
        else:
            return f"{food} is allergenic and cannot be eaten"

#####################################################################################################################
#####################################################################################################################


# 3. Rewrite the Human class bellow (without changing it's name), so that it inherits from the Animal class of the exercice 2.
# * You should override the 'has_allergy' method in the Human class, so that it now only returns True if the food is 'peanut'

class Human(Animal):
    def has_allergy(self, food):
        return food == "peanut"



#####################################################################################################################
#####################################################################################################################

# 4. Implement the Child class below, which inherets from Human (from exercice 3).
# * Instances of Child need to have a 'toy' attribute (string), which is defined during instantiation
# * This class should also have a 'playing_with_toy' method, which should return the 'toy' (string) that the Child has.
# * Other than that, a Child should behave exactly like a Human instance, so make sure it is inheriting all the logic from its parents '__init__' method



class Child(Human):

    def __init__(self, toy, *args, **kwargs):
        self.toy = toy
        super().__init__(*args, **kwargs)

    def playing_with_toy(self):
        return self.toy

#####################################################################################################################
#####################################################################################################################


# 5. Write code in the following __main__ function to test all classes, their attributes and functions.
# * Currently this function includes some examples tests, so you need to extend this code to include all needed tests.
if __name__ == '__main__':

    # Example code for testing

    # Problem 1 - Test
    my_instance = MyClass(some_val=90)
    assert my_instance.some_val == 90

    another_instance = MyClass(some_val=100)
    assert another_instance.plus_n(3) == 103

    # Problem 2 - Test
    digestive_system = DigestiveSystem()
    animal = Animal(digestive_system)
    assert isinstance(animal.digestive_system, DigestiveSystem)

    assert animal.eat_food("banana") == "banana has been processed."
    assert animal.eat_food("peanut") is None

    # Problem 3 - Test
    human = Human(digestive_system)
    assert human.has_allergy("peanut") == True
    assert human.has_allergy("banana") == False

    assert human.eat_food("banana") == "banana has been processed."
    assert human.eat_food("peanut") is None

    # Problem 4 - Test
    child = Child("car", "peanut", digestive_system)
    assert child.playing_with_toy() == "car"
    assert child.has_allergy("peanut") == True
    assert child.has_allergy("banana") == False

    assert child.eat_food("chocolate") == "chocolate has been processed."
    assert child.eat_food("peanut") is None




错误代码是:

img

  • 写回答

2条回答 默认 最新

  • allyfireshen 2023-02-18 02:20
    关注

    修改如下:

    # 1. Implement a class named "MyClass"
    # This class should have:
    # * During instantiation of this class, the 'some_val' parameter should be set as
    #   a variable with the same name in the instance
    # * Implement the method called 'plus_n' that takes one parameter (named 'n'), such that
    #   it should return the sum of instance's 'some_val' variable and 'n'
    class MyClass:
        def __init__(self, some_val):
            self.some_val = some_val
     
        def plus_n(self, n):
            return self.some_val + n
     
    #####################################################################################################################
    #####################################################################################################################
     
    # 2. Given two classes 'Animal' and 'DigestiveSystem, implement, using COMPOSITION the method 'eat_food' in the 'Animal' class.
    # * Animal instances should have a 'diggestive_system' attribute, which is the DigestiveSystem instance of that object.
    # * The eat_food method should PROCESS any 'food' (any string) that are not allergenic (use the method 'has_allergy' to check for this case)
    # * The DigestiveSystem is a class responsible for the PROCESS of any food eaten,
    #       so make use of this in the Animal.eat_food method (remember COMPOSITION!)
     
    class DigestiveSystem:
        """This class is already done for you
        don't changea any code on it.
        """
        def process_food(self, food):
            return f'processed-{food}'
     
     
    class Animal:
        def __init__(self):
            self.digestive_system = DigestiveSystem()
     
        def has_allergy(self, food):
            if food.lower() in ['peanut', 'milk']:
                return True
            return False
     
        def eat_food(self, food):
            if not self.has_allergy(food):
                return self.digestive_system.process_food(food)
            else:
                return f"{food} is allergenic and cannot be eaten"
     
    #####################################################################################################################
    #####################################################################################################################
     
     
    # 3. Rewrite the Human class bellow (without changing it's name), so that it inherits from the Animal class of the exercice 2.
    # * You should override the 'has_allergy' method in the Human class, so that it now only returns True if the food is 'peanut'
     
    class Human(Animal):
        def has_allergy(self, food):
            return food == "peanut"
     
     
     
    #####################################################################################################################
    #####################################################################################################################
     
    # 4. Implement the Child class below, which inherets from Human (from exercice 3).
    # * Instances of Child need to have a 'toy' attribute (string), which is defined during instantiation
    # * This class should also have a 'playing_with_toy' method, which should return the 'toy' (string) that the Child has.
    # * Other than that, a Child should behave exactly like a Human instance, so make sure it is inheriting all the logic from its parents '__init__' method
     
     
     
    class Child(Human):
     
        def __init__(self, toy, *args, **kwargs):
            self.toy = toy
            super().__init__(*args, **kwargs)
     
        def playing_with_toy(self):
            return self.toy
     
    #####################################################################################################################
    #####################################################################################################################
     
     
    # 5. Write code in the following __main__ function to test all classes, their attributes and functions.
    # * Currently this function includes some examples tests, so you need to extend this code to include all needed tests.
    if __name__ == '__main__':
     
        # Example code for testing
     
        # Problem 1 - Test
        my_instance = MyClass(some_val=90)
        assert my_instance.some_val == 90
     
        another_instance = MyClass(some_val=100)
        assert another_instance.plus_n(3) == 103
     
        # Problem 2 - Test
        digestive_system = DigestiveSystem()
        animal = Animal()
        assert isinstance(animal.digestive_system, DigestiveSystem)
     
        assert animal.eat_food("banana") == "banana has been processed." 
        '''
        因为animal.eat_food("banana")的执行结果为:processed-banana
        而 "processed-banana" 不等于 "banana has been processed."
        所以此处会抛出AssertionError异常,后面程序将不执行
        '''
        assert animal.eat_food("peanut") is None
     
        # Problem 3 - Test
        human = Human(digestive_system)
        assert human.has_allergy("peanut") == True
        assert human.has_allergy("banana") == False
     
        assert human.eat_food("banana") == "banana has been processed."
        assert human.eat_food("peanut") is None
     
        # Problem 4 - Test
        child = Child("car", "peanut", digestive_system)
        assert child.playing_with_toy() == "car"
        assert child.has_allergy("peanut") == True
        assert child.has_allergy("banana") == False
     
        assert child.eat_food("chocolate") == "chocolate has been processed."
        assert child.eat_food("peanut") is None
    
    

    结果如图:

    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 2月27日
  • 已采纳回答 2月19日
  • 创建了问题 2月18日

悬赏问题

  • ¥15 请提供一个符合要求的网页链接。
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码