PHP前端开发

python类的构造函数是什么

百变鹏仔 3周前 (02-06) #Python
文章标签 函数

python魔法方法:__init__( )方法,被称为构造方法。__init__()方法的魔力体现在只要实例化一个对象,这个方法就会在对象被创建时自动调用。实例化对象时是可以传入参数的,这些参数会自动传入__init__()方法中,可以通过重写这个方法来自定义对象的初始化操作。

总结:__init__()方法是一个特殊的方法,在对象实例化时会被调用,__init__()方法的作用是初始化。

例1:

class Myclass:    i = 123    def __init__(self,friend):        self.friend = friend     def func(self,myself):    #带有参数的类方法        self.myself = myself        return self.myself +"say hello to " + self.friend use_class = Myclass("xiaoming")print("调用类的属性:",use_class.i)print("调用类的方法:", use_class.func("xiaohong"))

输出结果:

立即学习“Python免费学习笔记(深入)”;

#调用类的属性: 123#调用类的方法: xiaohongsay hello to xiaoming