簡體   English   中英

python子類在它們之間共享常規功能

[英]python subclasses have general functions shared across them

我創建了一個基類和一個子類。 我將創建更多的子類,但是我有一些通用函數將在所有子類中使用。 這是設置它的正確方法嗎? 我假設將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()

您應該在基類上添加常規方法,然后從子類中調用它們:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM