【问题标题】:How to inherit a class' methods and have them access self member variables in python如何继承一个类的方法并让它们访问python中的self成员变量
【发布时间】:2011-09-01 20:38:57
【问题描述】:

我是 Python 的新手,我一直在尝试找出将一堆杂乱无章的类方法(访问成员变量)迁移到单独的 Utils.py 类型模块以进行清理的最佳方法。方法名称仍然需要由基类继承,但它们还需要能够访问parnet 类方法。我正在详细说明背景,因为我认为可能有更好的 python 方法来解决这个问题。

如果我试图通过继承来做到这一点,基本上我需要做以下事情:(我玩过 super,但我无法通过这种方式解决它)

class Graph(GraphUtils):
    graph_size = 10
    def print_size(self):
        print self.graph_size

class GraphUtils():
    def set_size(self, new_size)
        self.graph_size = new_size

if __name__ == "__main__":
    g = Graph()
    print "Graph default size: " + str(g.graph_size) # This is 10
    g.set_size(20)
    g.print_size() # I want it to print 20, but it'll print the default 10

我知道还有另一种方法可以统一将一个类的方法和变量导入另一个类,但我冒着命名空间冲突的风险。

我在类似案例中使用的一种技术,其中需要一个单独的模块在我们的库中显示为“附加组件”,如下所示:(“附加组件”的想法来自于有选择地分发附加组件的愿望Graph 类的功能,都与许可相关)

class Graph:
    ext = None
    graph_size = 10
    def __init__(self):
        self.ext = Extension()
        self.ext._graph = self

    def set_size(self, new_size):
        self.graph_size = new_size

class Extension:
    _graph = None
    def process(self):
        print "Processing graph size: " + str(self._graph.graph_size)

if __name__ == "__main__":
    g = Graph()
    print "Graph default size: " + str(g.graph_size) # This is 10
    g.set_size(20)
    g.ext.process()
    # Output: Processing graph size: 20

只是想知道你们认为最好的方法是什么,或者这是否可以在 Python 中合理(安全地)完成。 (2.6+)

谢谢!

【问题讨论】:

  • 您展示的代码甚至可以像您描述的那样工作——GraphUtils 必须在 Graph 可以在其上构建之前定义。当这两个类被交换时,它就像你想要的那样工作。

标签: python class inheritance


【解决方案1】:

解决方法是在类的__init__()方法中定义变量,并确保初始化继承的对象。

__init__() 是一个“神奇的”类方法,当从类定义中创建一个新对象时会调用它。

# Inherit object for new-style Python classes (recommended)
class GraphUtils(object):
    # Override the __init__() magic-method.
    def __init__(self):
        # Initialize the inherited object by executing its __init__() method.
        super(GraphUtils, self).__init__()

    def set_size(self, new_size):
        self.graph_size = new_size

# Inherit GraphUtils
class Graph(GraphUtils):
    def __init__(self):
        # Initialize the inherited GraphUtils object.
        super(Graph, self).__init__()
        # Declare the graph_size variable on creation of a new Graph object.
        self.graph_size = 10

    def print_size(self):
        print self.graph_size

if __name__ == "__main__":
    g = Graph()
    # It is recommended to use str.format() instead of string concatonation
    print "Graph default size: {}".format(g.graph_size) # will print "Graph default size: 10"
    g.set_size(20)
    g.print_size() # This will print 20

http://docs.python.org/reference/datamodel.html#basic-customization

http://docs.python.org/glossary.html#term-new-style-class

http://docs.python.org/library/functions.html#super

http://docs.python.org/library/string.html#string-formatting

【讨论】:

  • 头奖。刘易斯成功了!我会投票赞成这个,但我首先需要一个 15 代表。也许其他一些友好的成员可以为我做这件事。
猜你喜欢
  • 2020-02-18
  • 2017-03-16
  • 1970-01-01
  • 2015-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-26
  • 2020-04-24
相关资源
最近更新 更多