当前位置:   article > 正文

详解Python中def __init__(self)与def __init__(self.参数1、参数2······)的区别_def init(self,x:list)

def init(self,x:list)

两者的主要区别
1.初始化参数为空的表述方式不同
2. 初始化附参数的表达方式不同,结构2的self.name一定要指向上面的参数
3. 实例化时的方法不同

def init(self)与def init(self.参数1、参数2······)在类中常常被作为初始化使用,对于代码的简化,对代码中多次出现的类进行参数设定,提高代码的可读性有很大帮助,两者主要存在三个区别。

1.初始化参数为空的表述方式不同

  1. #def __init__(self)结构
  2. class student:
  3. def __init__(self):
  4. self.name = None
  5. self.score = None
  6. #def __init__(self.参数1、参数2······)结构
  7. class student:
  8. def __init__(self, name, score):
  9. self.name = name
  10. self.score = score

2.初始化附参数的表达方式不同,结构2的self,name一定要指向上面的参数

  1. #def __init__(self)结构
  2. class student:
  3. def __init__(self):
  4. self.name = A
  5. self.score = 18
  6. #def __init__(self.参数1、参数2······)结构
  7. class student:
  8. def __init__(self, name=A, score=18):
  9. self.name = name
  10. self.score = score

3.实例化时的方法不同
结构体1在实例化时需要先引用结构体,在结构体里进行参数更改

  1. #def __init__(self)结构
  2. class Student:
  3. def __init__(self):
  4. self.name = None
  5. self.score = None
  6. def print_score(self):
  7. print("%s score is %s" % (self.name,self.score))
  8. if __name__ == '__main__':
  9. # 创建对象s1
  10. s1 = Student()
  11. s1.name = "b"
  12. s1.score = 20
  13. s1.print_score()
  14. print(s1.__dict__)#看属性

结构体2在实例化时需要先引用结构体,在引用体的括号里进行更改

  1. #def __init__(self.参数1、参数2······)结构
  2. class Student:
  3. def __init__(self,name,score):
  4. self.name = name
  5. self.score = score
  6. def print_score(self):
  7. print("%s score is %s" % (self.name,self.score))
  8. if __name__ == '__main__':
  9. # 创建对象s1
  10. s1 = Student("b",20)
  11. s1.print_score()
  12. print(s1.__dict__)#看属性

总结

两种方式的使用方法上略微有区别,但功能上是一致的,习惯哪个用哪个就行。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/寸_铁/article/detail/761928
推荐阅读
相关标签
  

闽ICP备14008679号