赞
踩
两者的主要区别
1.初始化参数为空的表述方式不同
2. 初始化附参数的表达方式不同,结构2的self.name一定要指向上面的参数
3. 实例化时的方法不同
def init(self)与def init(self.参数1、参数2······)在类中常常被作为初始化使用,对于代码的简化,对代码中多次出现的类进行参数设定,提高代码的可读性有很大帮助,两者主要存在三个区别。
1.初始化参数为空的表述方式不同
- #def __init__(self)结构
- class student:
- def __init__(self):
- self.name = None
- self.score = None
-
- #def __init__(self.参数1、参数2······)结构
- class student:
- def __init__(self, name, score):
- self.name = name
- self.score = score
2.初始化附参数的表达方式不同,结构2的self,name一定要指向上面的参数
- #def __init__(self)结构
- class student:
- def __init__(self):
- self.name = A
- self.score = 18
- #def __init__(self.参数1、参数2······)结构
- class student:
- def __init__(self, name=A, score=18):
- self.name = name
- self.score = score
-
3.实例化时的方法不同
结构体1在实例化时需要先引用结构体,在结构体里进行参数更改
- #def __init__(self)结构
- class Student:
- def __init__(self):
- self.name = None
- self.score = None
-
- def print_score(self):
- print("%s score is %s" % (self.name,self.score))
-
- if __name__ == '__main__':
- # 创建对象s1
- s1 = Student()
- s1.name = "b"
- s1.score = 20
-
- s1.print_score()
- print(s1.__dict__)#看属性

结构体2在实例化时需要先引用结构体,在引用体的括号里进行更改
- #def __init__(self.参数1、参数2······)结构
- class Student:
- def __init__(self,name,score):
- self.name = name
- self.score = score
-
- def print_score(self):
- print("%s score is %s" % (self.name,self.score))
-
- if __name__ == '__main__':
- # 创建对象s1
- s1 = Student("b",20)
- s1.print_score()
- print(s1.__dict__)#看属性
-
两种方式的使用方法上略微有区别,但功能上是一致的,习惯哪个用哪个就行。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。