python初始化方法

2023年2月22日12:55:20

python可以用__init__函数进行初始化,子类中可以使用super函数和__init__进行初始化

#encoding:utf-8
class Person(object):
    def __init__(self,name,sex):
        self.name = name
        self.sex = sex

class Child(Person):                          # Child 继承 Person
    def __init__(self,name,sex,mother,father):
        Person.__init__(self,name,sex)        # 子类对父类的构造方法的调用
        self.mother = mother
        self.father = father


class Child_chg(Person):                          # Child 继承 Person
    def __init__(self,name,sex,mother,father):
        # Person.__init__(self,name,sex)        # 子类对父类的构造方法的调用
        super(Child_chg, self).__init__(name,sex)
        self.mother = mother
        self.father = father


# class Child_chg(Person):                          # Child 继承 Person
#     def __init__(self,name,sex,mother,father):
#         # Person.__init__(self,name,sex)        # 子类对父类的构造方法的调用
#         super(Child_chg, self).__init__()
#         self.mother = mother
#         self.father = father



May = Child("May","female","April","June")
print(May.name,May.sex,May.mother,May.father)

May_chg = Child_chg("May","female","April","June")
print(May_chg.mother,May_chg.father)

  • 作者:拾光123
  • 原文链接:https://blog.csdn.net/kkkxiong1/article/details/84952162
    更新时间:2023年2月22日12:55:20 ,共 860 字。