4

在通过 codacy 审查一些代码时,Codacy 给出了以下代码的问题:

def MyClass(OldClass):
    def __init__(self, arg1, arg2, *args, **kwargs)
        self.arg1 = arg1
        self.arg2 = arg2
        super(OldClass, self).__init__(*args, **kwargs)

有以下解释:

为什么这是一个问题?

例如,使用基类作为第一个参数调用 super() 是错误的:

class AnotherOldStyleClass(OldStyleClass):
    def __init__(self):
        super(OldStyleClass, self).__init__() The super invocation 

应该:

super(AnotherOldStyleClass, self).__init__()

似乎希望我这样做:

def MyClass(OldClass):
    def __init__(self, arg1, arg2, *args, **kwargs)
        self.arg1 = arg1
        self.arg2 = arg2
        super(OldClass, self).__init__(*args, **kwargs)

或者也许是这样:

def MyClass(OldClass):
    def __init__(self, arg1, arg2, *args, **kwargs)
        super(MyClass, self).__init__(*args, **kwargs)
        self.arg1 = arg1
        self.arg2 = arg2

有人可以告诉我其中哪些是正确的,为什么这是首选行为?

作为参考,这里是我使用选项 2 找到的示例。

编辑:这是我的代码,因为它完全显示。这解释了我的错误:

class TransferToBigQuery(GoogleCloudStorageToBigQueryOperator): 
    """Class to transfer data from Google cloud storage to Big Query""" 
    def __init__( 
        self, id, bucket, destination_project_dataset_table, source_objects=None, 
        schema_fields=None, schema_object=None, source_format='CSV', 
        create_disposition='CREATE_IF_NEEDED', 
        skip_leading_rows=0, write_disposition='WRITE_EMPTY', 
        field_delimiter=',', max_id_key=None, file_xcom=None, 
        bigquery_conn_id='bigquery_default', 
        google_cloud_storage_conn_id='google_cloud_storage_default', 
        delegate_to=None, schema_update_options=(), *args, **kwargs): 
        super(GoogleCloudStorageToBigQueryOperator, self).__init__(*args, 
                                                               **kwargs) 

为什么推荐这个?

4

1 回答 1

1

我希望下一个例子能解释不同之处

class Grandparent(object):
    def hello(self):
        print "hi, I am Grandparent"

class Parent(Grandparent):
    def hello(self):
        print "hi, I am Parent"

class Child(Parent):
    def test(self):
        super(Parent, self).hello()   # print "hi, I am Grandparent"
        super(Child, self).hello()  # print "hi, I am Parent"

    def proper_way_to_do_same(self):
        Grandparent.hello(self)   # print "hi, I am Grandparent"
        Parent.hello(self)  # print "hi, I am Parent"
于 2019-12-19T13:35:42.717 回答