如何继承类的方法并让它们在python中访问自己的成员变量

时间:2011-09-01 20:38:57

标签: python class inheritance

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

基本上我需要做类似以下的事情,如果我试图通过继承来做到这一点:(我玩过超级,但我一直无法解决这个问题)

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 +)

谢谢!

1 个答案:

答案 0 :(得分:4)

解决方法是在类的__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