子类带有额外参数的Python类继承

huangapple go评论80阅读模式
英文:

child class with extra arguments python class inheritance

问题

我编写了一个父类

```python
class Parent():
    def __init__(self, spark_session=None):
        try:
            # 实例化 Spark 会话
            self.spark = spark_session
            if not self.spark:
                self.spark = SparkSession.builder.config("spark.sql.debug.maxToStringFields", 1000).appName("SparkTest") \
                    .getOrCreate()
        except Exception as e:
            print("初始化 Spark 和日志记录失败: {}".format(e))

然后子类在其构造函数中有一个额外的参数,即路径:

class Child(Parent):
    def __init__(self, path, spark=None):
        self.spark = super().__init__(spark)
        self.path = path

然后当我写下这段代码:

a = Child("path", None)
print(a.spark)

对于:

self.spark = spark_session

我得到了:

AttributeError: 'NoneType' object has no attribute 'spark' None

有任何想要修复这个问题并使 Spark 对象按预期实例化的想法吗?

谢谢。


<details>
<summary>英文:</summary>

I wrote a parent class:

```python
class Parent():
    def __init__(self, spark_session=None):
        try:
            # Instantiate Spark Session
            self.spark = spark_session
            if not self.spark:
                self.spark = SparkSession.builder.config(&quot;spark.sql.debug.maxToStringFields&quot;, 1000).appName(&quot;SparkTest&quot;) \
                    .getOrCreate()
        except Exception as e:
            print(&quot;Initialization of spark &amp; logging couldn&#39;t be performed: {}&quot;.format(e))

Then the child class has an extra argument in its constructor which is path:

class Child(Parent):
    def __init__(self, path, spark=None):
        self.spark = super().__init__(spark)
        self.path = path

Then when I write this:

a = Child(&quot;path&quot;, None)
print(a.spak)

For:

self.spark = spark_session

I get:

AttributeError: &#39;NoneType&#39; object has no attribute &#39;spark&#39; None

Any idea how to fix this and make spark object instantiate as expected.

Regards

答案1

得分: 1

self.spark = super().__init__(spark):

self.spark = super().__init__(spark):
self.spark = super().__init__(spark):

__init__ 不是构造函数。它初始化对象的属性并返回 None,而不是对象本身。

一旦调用 super().__init__self.spark 将自动初始化。

请注意,我还稍微更改了 Parent.__init__。在您的代码中,如果引发异常,self.spark 没有定义,这将导致后续出现其他错误。

class Parent:
    def __init__(self, spark_session=None):
        self.spark = spark_session            
        try:  
            if not self.spark:
                self.spark = SparkSession.builder.config("spark.sql.debug.maxToStringFields", 1000).appName("SparkTest") \
                .getOrCreate()
        except Exception as e:
            print("初始化 Spark 和记录无法执行: {}".format(e))
                

class Child(Parent):
    def __init__(self, path, spark=None):
        super().__init__(spark)
        self.path = path
英文:

self.spark = super().__init__(spark)

__init__ is not a constructor. It initializes the object's attributes and returns None, not the object.

self.spark will be automatically initialized once you call super().__init__.

Note I also changed Parent.__init__ a bit. In your code self.spark is not defined in case an exception is raised which will lead to other errors down the road.

class Parent:
    def __init__(self, spark_session=None):
        self.spark = spark_session            
        try:  
            if not self.spark:
                self.spark = SparkSession.builder .config(&quot;spark.sql.debug.maxToStringFields&quot;, 1000).appName(&quot;SparkTest&quot;) \
                .getOrCreate()
        except Exception as e:
            print(&quot;Initialization of spark &amp; logging couldn&#39;t be performed: {}&quot;.format(e))
            

class Child(Parent):
    def __init__(self, path, spark=None):
        super().__init__(spark)
        self.path = path

huangapple
  • 本文由 发表于 2020年1月6日 19:22:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/59611229.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定