qq_39372401
qq_39372401
采纳率74.1%
2019-09-07 08:43

python __init__方法子类如何在继承父类的基础上进行拓展

5

举例说明:
class A():
def init(self,name,age):
self.name =name
self.age = age

class B(A):
def init(self,score):
pass

问题:如何设置,让B类在创建实例对象时,name和age必填,score可以进行选填

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • weixin_42062762 weixin_42062762 2年前

    class A():
    def init(self,name,age):
    self.name =name
    self.age = age

    class B(A):
    def init(self,name,age):
    super().__init__(name,age)
    self.score = 0
    def say(self):
    print("name = %d" % self.name)
    print("age = %d" % self.age)
    print("score = %s" % self.score)

    data = B(1,2)
    data.say()
    还有这种 :好好看下区别 当然貌似还有继承多个类 我也不太懂
    class A():
    def init(self,name,age):
    self.name =name
    self.age = age
    def say(self):
    print("这是父类")

    class B(A):
    def init(self,name,age):
    A.__init__(self,name,age)
    self.score = 0
    def say(self):
    print("name = %d" % self.name)
    print("age = %d" % self.age)
    print("score = %s" % self.score)
    def extend2(self):
    A.say(self)

    data = B(1,2)
    data.say()
    data.extend2()

    点赞 1 评论 复制链接分享