zoukankan      html  css  js  c++  java
  • 随身笔记 Python中__init__和self的意义和作用

    随身笔记
    Python中__init__和self的意义和作用
     
    
    init()方法,在创建一个对象时默认被调用,不需要手动调用
    
    复制代码
    #init方法
    class Car():
        def __init__(self):
             self.num = 4
             self.color = '红色'
        def taxi(self):
            print("出发去西湖!")
    #创建对象
    test = Car()
    print("车的颜色为:%s"%test.color)
    print("车轮胎的数量:%s"%test.num)
    
    '''结果输出:'''
    
    #车的颜色为:红色
    #车轮胎的数量:4
    
    
     
    复制代码
    带有参数的__init__方法时,在创建实例的时候,就不能传入空的参数了,必须传入与__init__方法匹配的参数,但self不需要传,Python解释器自己会把实例变量传进去:
    
    如果不传参数的话则会报错:TypeError: __init__() missing 2 required positional arguments: 'name' and 'age'  具体的见一下面的例子
    
    复制代码
    #init方法
    class Sutdent:
        def __init__(self,name,age):
             self.name = name
             self.age = age
        def taxi(self):
            print("出发去西湖!")
    #创建对象
    test = Sutdent('Sample_天',3)
    print("学生姓名:%s"%test.name)
    print("学生年龄:%s"%test.age)
    
    #学生姓名:Sample_天
    #学生年龄:3
    

      原文:https://www.cnblogs.com/xh0203/p/12663621.html

  • 相关阅读:
    LeetCode题解之Leaf-Similar Trees
    LeetCode题解之 Increasing Order Search Tree
    建立git仓库的步骤
    Jquery-1(基础)
    JavaScript-12(脚本化CSS)
    JavaScript-11(DOM文档对象模型)
    JavaScript-10(JavaScript事件)
    JavaScript-实现下拉菜单
    JavaScript-9(BOM浏览器对象模型)
    JavaScript-字符与编码转换
  • 原文地址:https://www.cnblogs.com/isme-zjh/p/13444871.html
Copyright © 2011-2022 走看看