python子类具有跨它们共享的一般功能

时间:2015-11-19 12:08:30

标签: python

我已经创建了一个基类和一个子类。我将创建更多的子类,但是我有一些将在所有子类中使用的通用函数。这是正确的设置方式吗?我假设将def添加到基类然后在每个子类中调用它会更容易。可以做或推荐吗?

""" 
Base class for all main class objects 
"""
class Node(object):
    def __init__(self, name, attributes, children):
        self.name = name
        self.attributes = attributes if attributes is not None else {}
        self.children = children if children is not None else []

"""
contains the settings for cameras
"""
class Camera(Node):
    def __init__(self, name="", attributes=None, children=None, enabled=True):
        super(Camera, self).__init__(name=name, attributes=attributes, children=children)
        self.enabled = enabled

        # defaults
        add_node_attributes( nodeObject=self)


# General class related functions
# ------------------------------------------------------------------------------
""" Adds attributes to the supplied nodeObject """
def add_node_attributes(nodeObject=None):

    if nodeObject:
        nodeObject.attributes.update( { "test" : 5 } )


# create test object
Camera()

1 个答案:

答案 0 :(得分:1)

您应该在基类上添加常规方法,并从子类中调用它们:

class Node(object):
    def __init__(self, name, attributes, children):
        self.name = name
        self.attributes = attributes if attributes is not None else {}
        self.children = children if children is not None else []
    def add_node_attributes(self):
        self.attributes.update( { "test" : 5 } )

这使您可以最大限度地利用继承。您的子类将使用方法add_node_attributes

c=Camera()
c.add_node_attributes()

您也可以在子类中调用它:

class Camera(Node):
    def __init__(self, name="", attributes=None, children=None, enabled=True):
        super(Camera, self).__init__(name=name, attributes=attributes, children=children)
        self.enabled = enabled

        # defaults
        self.add_node_attributes()