Python面向对象(构造方法)

day24

构造方法

特殊作用:在obj=classname()中1.创建对象2.通过对象执行类中的一个特殊方法

1 class Bar:
2     def __init__(self):
3         print("123")
4     def  foo(self, argc):
5         print(argc)
6 z = Bar()

创建对象的过程中会执行特殊方法__init__(),即为构造方法。

执行结果:

123

Process finished with exit code 0

完整的构造方法

 1 class Bar:
 2     def __init__(self, name, age):
 3         self.n = name
 4         self.a = age
 5     def  foo(self, argc):
 6         print(self.n, argc)
 7 
 8 z = Bar('alex', 84)
 9 z.n = 'alex' #z就是self ,与self.n = name一样
10 z.foo(112358)

第9行的代码效果和第3行效果一致,。

执行结果:

alex 112358

Process finished with exit code 0

####################################################################################################


 1 class Person:
 2     def __init__(self, name, age):
 3         self.n = name
 4         self.a = age
 5         self.style = "AB"#都是AB血型
 6 
 7     def show(self):
 8         print("%s~%s~%s" %(self.n, self.a, self.style))
 9 
10 lihuan = Person('李欢', 18)
11 lihuan.show()
12 hu = Person("", 73)
13 hu.show()

第5行,每个对象血型都为AB,不需要在声明对象时重复传入参数。

如果多个函数中有一些相同参数时,可以转换成面向对象形式。

执行结果:

李欢~18~AB~73~AB

Process finished with exit code 0
原文地址:https://www.cnblogs.com/112358nizhipeng/p/9815845.html