• python解释def __init__(self, *args, **kwargs)


    def init(self, *args, **kwargs): 其含义代表什么?

    • 这种写法代表这个方法接受任意个数的参数
    • 如果是没有指定key的参数,比如单单’apple’,‘people’,即为无指定,则会以list的形式放在args变量里面
    • 如果是有指定key的参数,比如item='apple’这种形式,即为有指定,则会以dict的形式放在kwargs变量里面
    def test(*args,**kwargs):
        print("无指定的参数为:")
        for i in args:
            print(i)
        print("有指定的参数为:")
        for key,value in kwargs.items():
            print(key, "=",value)
    
    test('this','that',item="BTC",price="20000USD")
    
    '''
    无指定的参数为:
    this
    that
    有指定的参数为:
    item = BTC
    price = 20000USD
    '''
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    Class 的定义

    # MyClass作为类的名字 
    class MyClass:
    	# 函数 __init__用来录入参数 放在self里面
        def __init__(self,x,y):
            self.x = x
            self.y = y
        # method_1函数,可以用上面__init__的参数,同时也可以自己另加参数使用
        def method_1(self,a):
            print("method_1 called")
            return a*self.x
        #method_2函数,同上。
        def method_2(self):
            return self.x
        
    # 上面的类,名字为MyClass, 有两个函数 作为属性,可以直接调用,调用方法如下:
    # 需要放入两个参数作为x,y的值,放入self里面
    my_class = MyClass(1,2)
    # 调用类里面的函数 method_1
    print(my_class.method_1(5))
    # output如下
    # method_1 called
    # 5
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    subclass的使用方法

    #定义子类的名字为MySubClass,加上括号继承之前的类MyClass
    class MySubClass(MyClass):
    	# 还是之前的函数__init__来录入参数,同时加入一个**kwargs 来录入另一个类的参数 
        def __init__(self,z,**kwargs):
            self.z = z 
            #用super()来继承父类的参数 
            super().__init__(**kwargs)
        #定义这个子类的函数,可以使用这个类的参数 和继承的另一个类的参数 
        def method_3(self,a):
            print("subclass method called")
            return a*self.x + self.z
    
        
    # z=10为子类的参数,x=.1,y=.2为继承的类的参数 ,同时调用。
    my_subclass = MySubClass(z=10,x=.1,y=.2)
    print(f"调用method3:{my_subclass.method_3(5):.3f}")
    print(f"调用method1:{my_subclass.method_2():.3f}")
    #output为
    subclass method called
    调用method3:10.500
    调用method1:0.100
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
  • 相关阅读:
    stm32cubemx图形化配置之 FreeRTOS选项中CMSIS_V1和CMSIS_V2的区别
    修复Windows上“发生意外错误”问题的5种方法,总有一种适合你
    批量上传图片添加水印
    【C++ Primer Plus学习记录】读取数字的循环
    快速入门XPath语法,轻松解析爬虫时的HTML内容
    五四青年节,今天要学习。汇总5道难度不高但可能遇到的JS手写编程题
    9.30号作业
    BCG ribbon在对话框中使用
    多线程的重要资料-信号量
    C++ 事件处理机制 定时器应用
  • 原文地址:https://blog.csdn.net/a1137588003/article/details/133254644