close

了解 super() 、self 和 *args and **kwargs 用法

在 python 物件方法中,如果存取一個 class 或者 instance 中的變數, 那麼在物件方法宣告參數時,就必須要有一個 self 當作第一個參數。
self就是代表該 instance 自身
#-------------------------

內建函數 (function) super() ,用為呼叫父類別定義的方法

super([type [,object-or-type]]) Return a **proxy object** that delegates method calls to a **parent or sibling** class of type.

class MyParentClass():
def __init__(self, x, y):
pass

class SubClass(MyParentClass):
def __init__(self, x, y):super().__init__(x, y)  # 呼叫父類別__init__()

我們需要在子類別初始化父類別,python 的super 函數簡化設計 

原文網址:https://kknews.cc/zh-tw/other/29r9qy.html

#----------------------------------

*args and **kwargs 用法

Example 1 :

#  傳入字串資料
def print_args(d1, d2, d3):
    print(d1, d2, d3)

data = ('foo', 'bar', 'baz')
print_args(*data)
>>> foo bar baz

# 傳入數值資料
def print_args(*args):
    for arg in args:
        print(arg)
print_args(1, 2, 3)
>>> 1
>>> 2
>>> 3

def print_args(*args):
    print(args)
print_args(1, 2, 3)
>>> (1, 2, 3)

# 傳出數值資料
def print_args(a, b, c, *args):
    print(a, b, c, args)
print_args(1, 2, 3, 4, 5)
>>> 1 2 3 (4, 5)


def print_kwargs(**kwargs):
    print(kwargs)
print_kwargs(foo='bar', hello='world')
>>> {'foo': 'bar', 'hello': 'world'}

def print_kwargs(latitude=None, longitude=None):
    print(latitude, longitude)

data = {'latitude': 0.00, 'longitude': 1.00}
print_data(**data)
>>> 0.00 1.00

def print_kwargs(lat=None, long=None, **kwargs):
    print(lat, long, kwargs)
print_kwargs(1, 2, data='other')
>>> 1 2 {'data': 'other'}

# 包含在繼承內

class Base(object):
    def __init__(self, *args, data=None, **kwargs):
        print('data is: ', data)

class MyBaseObject(Base):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

class MyObject(MyBaseObject):
    def __init__(self, *args, game=None, **kwargs):
        super().__init__(*args, **kwargs)
        print('game is: ', game)

my_data = {'game': 'UT', 'data': '3d'}
MyObject(**my_data)
>>> data is: 3d
>>> game is: UT

 

example 2 :

class A(object):
 
    def __init__(self, *args, **kwargs):
        super(A, self).__init__(*args, **kwargs)
        self.number = kwargs['number']
 
    def helloA(self):
        return self.number
 
class B(object):
 
    def __init__(self, *args, **kwargs):
        super(B, self).__init__()
        self.message = kwargs['message']
 
    def helloB(self):
        return self.message
 
class C(A,B):
 
    def __init__(self, *args, **kwargs):
        # Notice: only one call to super... due to mro
        super(C, self).__init__(*args, **kwargs)
 
    def helloC(self):
        print "Calling A: ", self.helloA()
        print "Calling B: ", self.helloB()  
 
def main():
    c = C(number=42, message="Joe")
    c.helloC()
 
if __name__ == '__main__':
    main()

 

$ python mrotest.py 
Calling A:  42
Calling B:  Joe

回主目錄

 

 

arrow
arrow

    stanley 發表在 痞客邦 留言(0) 人氣()