【问题标题】:Classes, Objects, Inheritance?类、对象、继承?
【发布时间】:2016-09-24 16:41:08
【问题描述】:

我应该创建三个类:父类、子类 1 和子类 2。
Child 1 和 2 应该继承自 Parent 类。 所以我相信我已经做到了。

class Parent:
    """Parent Object"""

    def __init__(self):
        self.greeting = "Hi I'm a Parent Object!"


class ChildA(Parent):

    def __init__(self):
        childclass.__init__(self)
        self.childgreeting = "Hi I'm a Child Object!"


class ChildB(Parent):
    pass

现在我必须编写一个父对象和子对象,它们将打印出各自的字符串。
这就是我感到困惑的地方:我已经在它们的类中输入了它们是子对象或父对象的字符串。
但是如何让它们作为对象打印?

我的代码是这样开始的。

class Parent(object):

class ChildA(object):

class ChildB(object):

如何打印这些字符串让我很头疼。
而且我感觉我的 ChildA 类代码也不正确。

谁能帮帮我?

【问题讨论】:

  • 你的意思是类名作为字符串?
  • 如果Parent确实是一个parent,那么为什么ChildA和ChildB继承自object?
  • 顺便说一句,childclass.__init__ 不起作用,因为 'childclass' 没有定义
  • 应该是Parent有greeting属性,childA有greeting属性,childB有"pass"。之后,我应该创建三个对象,将它们各自的字符串属性打印到控制台!

标签: python class object inheritance


【解决方案1】:

孩子 1 和 2 应该继承自 Parent 类。所以我相信我已经做到了

是的,在第一个代码中,您有,但在第二个代码中没有。

我必须编写一个父对象和子 1 和 2 对象,它们将打印出它们各自的字符串

好的……

p = Parent()
child_a = ChildA()

print(p.greeting) 
print(child_a.childgreeting)

但是 - ChildA() 不起作用,因为 __init__ 应该是这样的

class ChildA(Parent):

    def __init__(self):
        super().__init__() # This calls the Parent __init__
        self.childgreeting = "Hi I'm a Child Object!"

现在,上面的代码可以工作了。

但是,我假设您希望覆盖 greeting 属性?否则你会得到这个

print(child_a.greeting) # Hi I'm a Parent Object!
print(child_a.childgreeting) # Hi I'm a Child Object!

如果是这种情况,您只需将childgreeting 更改为greeting。然后,从第一个例子开始

print(p.greeting) # Hi I'm a Parent Object!
print(child_a.greeting)  # Hi I'm a Child Object!

如何让它们作为对象打印?

不完全确定您的意思,但如果您将 __str__ 定义为返回 greeting

class Parent:
    """Parent Object"""

    def __init__(self):
        self.greeting = "Hi I'm a Parent Object!"

    def __str__(self):
        return self.greeting

现在的例子变成了

print(p) # Hi I'm a Parent Object!
print(child_a)  # Hi I'm a Child Object!

【讨论】:

  • 是的!这正是我想知道的,精彩地解释了。如果我的问题有点含糊,我很抱歉,我尽量用最好的方式来表达。
  • 不用担心。如果可以,请随时accept the answer。
【解决方案2】:
class Parent(object):

    def __init__(self):
        self.greeting = "Hi I am a parent"
    def __str__(self):
        return self.greeting


class Child(Parent):

    def __init__(self):
        super(Child, self).__init__()
        self.greeting = "Hi I am Child"

    def __str__(self):
        return self.greeting


p = Parent()
print(p)
c = Child()
print(c)

此方法可以帮助您使用 'print()' 语句打印出个别班级的问候语。但是如果你想直接获取 self.greeting 属性你应该使用

p = Parent()
print(p.greeting)

希望我能理解你,因为你的问题似乎没有得到正确解释......

【讨论】:

  • 是的!感谢您的理解!抱歉有点含糊!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-24
  • 1970-01-01
  • 1970-01-01
  • 2020-10-09
  • 2012-01-05
  • 2011-10-08
  • 1970-01-01
相关资源
最近更新 更多