20191225_Python构造函数知识以及相关注意事项

Python构造函数格式为__init__()    注:下划线为两个而不是一个

可以有无参构造

instance:

 class city:
     def printout(self,first,second):
         print(first+second)
        
 demo = city()
 demo.printout(1,2)

就是不用写构造器,系统自动生成

但是类里的方法必须有一个参数,用以表示类自身

不加就会报错,在外部调用的时候直接忽略这个参数即可

也可以由有参构造

instance

class city:
    def __init__(self):
        print("构造测试")
    
    def printout(self,first,second):
        print(first+second)
        
demo = city()
demo.printout(1,2)
class city:
    def __init__(self,name,age):
        self.name = name
        self.age = age
        
    def printout(self,first,second):
        print(self.name)
        print(self.age)
        print(first)
        print(second)
        
demo = city("pan",18)
demo.printout(1,2)

如果要写出构造函数,也和其它内部函数一样,必须加上一个变量来表示类自身

否则会报错

外部调用忽略即可

猜你喜欢

转载自www.cnblogs.com/lavender-pansy/p/12096594.html