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
'''
Class 的定义
class MyClass :
def __init__ ( self, x, y) :
self. x = x
self. y = y
def method_1 ( self, a) :
print ( "method_1 called" )
return a* self. x
def method_2 ( self) :
return self. x
my_class = MyClass( 1 , 2 )
print ( my_class. method_1( 5 ) )
subclass的使用方法
class MySubClass ( MyClass) :
def __init__ ( self, z, ** kwargs) :
self. z = z
super ( ) . __init__( ** kwargs)
def method_3 ( self, a) :
print ( "subclass method called" )
return a* self. x + self. z
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 } " )
subclass method called
调用method3: 10.500
调用method1: 0.100