python如何在多重继承中继承/重写函数?

时间:2018-07-27 14:50:09

标签: python inheritance multiple-inheritance virtual-functions abstraction

我有以下代码:-

import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.dynamicframe import DynamicFrame
from awsglue.job import Job

from pyspark.sql import Row
from faker import Faker 

## @params: [JOB_NAME]
args = getResolvedOptions(sys.argv, ['JOB_NAME'])

sc = SparkContext()
glueContext = GlueContext(sc)
spark = glueContext.spark_session
job = Job(glueContext)
job.init(args['JOB_NAME'], args)

# number of records
num_records = int(1e6)

# faker settings
fake = Faker('nl_NL')
fake_line = lambda x: Row(fake.sha256(), fake.name(), fake.street_name(), fake.province(), fake.country(), fake.phone_number(), fake.email(), fake.iban())
df_header = ['sha256', 'name', 'streetname', 'province', 'country', 'phonenumber', 'email', 'iban']

# create 
df = sc.parallelize(range(0, num_records)).map(fake_line).toDF(schema = df_header)
dynamic_df = DynamicFrame.fromDF(df, glueContext, 'dynamic_faker')

glueContext.write_dynamic_frame.from_options(
frame = dynamic_df,
connection_type = "s3",
connection_options = {"path": "s3://bucket-path"},
format = "csv",
transformation_ctx = "")

job.commit()

我得到的输出是:-

class A(object):
    def __init__(self):
        print "I'm in A"

    def awesome_function(self):
        raise NotImplementedError

class B(A):
    def awesome_function(self):
        print "Implemented in B"

class C(object):
    def awesome_function(self):
        print "Implemented in C"

class D(A,C):
    def another_function(self):
        print "hello world"

class E(C,A):
    def another_function(self):
        print "hello world"

try:
    a = A()
    a.awesome_function()
except Exception as e:
    print "NotImplementedError"
    pass

try:
    b = B()
    b.awesome_function()
except Exception as e:
    print "NotImplementedError in b"

try:
    d = D()
    d.awesome_function()
except Exception as e:
    print "NotImplementedError in d"

try:
    e = E()
    e.awesome_function()
except Exception as s:
    print "NotImplementedError in e"

为什么E和D不起作用?

我假设函数按照从继承中提到的顺序从左到右填充在类的dict中。但是,似乎是从右向左?

1 个答案:

答案 0 :(得分:1)

您可以检查方法的解析顺序:

print D.__mro__
(<class '__main__.D'>, <class '__main__.A'>, <class '__main__.C'>, <type 'object'>)
print E.__mro__  
(<class '__main__.E'>, <class '__main__.C'>, <class '__main__.A'>, <type 'object'>)

如您所见,类D首先进入超类A(并找到了awesome_function方法),这是您在继承中从左到右列出的顺序。