class Person():#首字母大写,冒号结尾 def introduce(self): print("my name is whm") print("nihao") p=Person()#实例化 p.introduce() #=========构造函数===========# class Test(): def __init__(self): print("我是构造函数,每次实例化我都会运行一次!") t=Test() '''说明:如果类里面没有定义构造函数,系统会自行新建一个构造函数,只不过构造函数没有内容而已''' ###构造函数的使用### class Student(): def __init__(self,name,age):#构造函数增加参数 self.name=name self.age=age def introduceself(self): print("My name is %s and i\'m %d years old !"%(self.name,self.age)) y=Student("04vn",12)#实例化增加参数 y.introduceself()
运行结果:
标签: Python python学习笔记