小编Nik*_*Nik的帖子

Scala:包对象与包内的单例对象

我想将一组类似的函数分组到 scala 的库中。这是我在其他地方看到的两种方法。我想了解两者之间的差异。

包中定义的单例对象

// src/main/scala/com/example/toplevel/functions.scala
package com.example.toplevel

object functions {
  def foo: Unit = { ... }
  def bar: Unit = { ... }
}
Run Code Online (Sandbox Code Playgroud)

封装对象

// src/main/scala/com/example/toplevel/package.scala
package com.example.toplevel

package object functions {
  def foo: Unit = { ... }
  def bar: Unit = { ... }
}
Run Code Online (Sandbox Code Playgroud)

比较

据我所知,第一种方法需要functions在您想要使用其功能时显式导入该对象。而包对象方法允许包中的任何内容functions访问这些方法而无需导入它们。

即,com.example.toplevel.functions.MyClass可以隐式访问com.example.toplevel.functions.foo

我的理解正确吗?

如果 中没有定义类com.example.toplevel.functions,则这些方法似乎是等效的,这是正确的吗?

scala library-design

6
推荐指数
1
解决办法
1997
查看次数

Python - 使用基类方法更新子属性

我花了一天的时间试图找到这个问题的答案,但一无所获。

假设我有几个类,每个类都包含与其他类相同的方法。

class A:
    def __init__(self, attr1, attr2, color):
        self.__attr1 = attr1
        self.__attr2 = attr2
        self.__color = color

    def set_color(self, color):
        self.__color = color

class B:
    def __init__(name, attr3, attr4, color):
         self.__attr3 = attr3
         self.__attr4 = attr4
         self.__color = color

    def set_color(self, color):
        self.__color = color
Run Code Online (Sandbox Code Playgroud)

在此示例中,相同的方法被简化为只有一个相同的方法 set_color,以说明我正在尝试执行的操作。

有没有办法消除重复代码,也许使用如下抽象类?

class Parent:
    def set_color(self, color):
        self.__color = color

class A(Parent):
    def __init__(self, attr1, attr2, color):
        self.__attr1 = attr1
        self.__attr2 = attr2
        self.__color = color


class B(Parent):
    def __init__(name, attr3, attr4, color): …
Run Code Online (Sandbox Code Playgroud)

python inheritance abstract-class object-oriented-analysis

2
推荐指数
1
解决办法
1793
查看次数