【问题标题】:Need help in Classes and Objects in Python [duplicate]在 Python 中的类和对象方面需要帮助 [重复]
【发布时间】:2018-08-12 23:32:06
【问题描述】:

问题陈述:

考虑一些值:

水果 ---> 苹果(红色,(3,2),有机), 橙子(橙子,(5,2),非有机) 等等……

我想将父类定义为 Fruits,然后在此父类中希望这些对象定义多个值。

然后,如果条件匹配并且创建了橘子类,我想运行一个仅适用于橘子类的特定函数。

我不熟悉 Python 中如此复杂的编程。

也欢迎提出建议!

【问题讨论】:

  • 元组是什么意思?,我还想你想要 Python 2.x?
  • 只是一个例子,想展示值的层次结构...... Python 2.x
  • 您能否举例说明您迄今为止所做的尝试以及遇到的问题?

标签: python


【解决方案1】:

你的问题真的很模棱两可。

您说您希望父类 Fruits 包含 类型为 Orange/Apple 等的对象。但您也说取决于获得的类创造了你想做的事。

*如果条件匹配... . (什么条件??)你没有指定什么条件。根据您提供的内容,我对答案应该是什么做出了解释。

class Fruit(object):
    color = None
    values = None
    nature = None

    def __init__(self, color, values, nature):
        self.color = color
        self.values = values
        self.nature = nature

class Orange(Fruit):
    color = "Orange"

    def __init__(self, values, nature):
        super(Orange, self).__init__(self.color, values, nature)

class Apple(Fruit):
    color = "Red"

    def __init__(self, values, nature):
        super(Apple, self).__init__(self.color, values, nature)



# a = Fruit("Green", (3,4), "Organic")
l = []
l.append(Fruit("Green", (3,4), "Organinc"))
l.append(Orange((3,4), "Non Organic"))
l.append(Apple((4,3), "Organic"))

print l

for f in l:
    if type(f) is Orange:
        print "Found an orange"

【讨论】:

    【解决方案2】:

    看起来你需要使用多重继承?

    class Fruits(object):
        def __init__(self, fruit):
            print fruit + "is a fruit"
    
    class Organic(Fruits):
        def __init__(self, fruit):
            print fruit + "is organic"
            super(Organic, self).__init__(fruit)
    
    class Colored(Organic):
        def __init__(self, fruit, color):
            print fruit + "is " + color
            super(Colored, self).__init__(fruit)
    
    class Apple(Colored, Organic):
        def __init__(self):
            super(Apple, self).__init__("apple", "red")
    
    apple = Apple()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-10
      • 2010-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多