需要Python类和对象方面的帮助吗

2024-06-25 23:55:53 发布

您现在位置:Python中文网/ 问答频道 /正文

问题陈述:

考虑以下值:

水果--->; 苹果(红色,(3,2),有机), 橙子(橙子,(5,2),非有机) 等等。。。你知道吗

我想将父类定义为水果,然后在父类中定义这些具有多个值的对象。你知道吗

然后如果条件匹配并且创建了类Oranges,我想运行一个只针对类Oranges的特定函数。你知道吗

我对Python中如此复杂的编程还不熟悉。你知道吗

开放的建议,以及!你知道吗


Tags: 对象函数gt苹果定义编程条件建议
2条回答

你的问题真是模棱两可。你知道吗

您说希望父类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"

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

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()

相关问题 更多 >