繁体   English   中英

为类方法调用私有方法:python

[英]calling private methods for class method: python

我试图在python中实现多个构造函数,(通过在线搜索)建议之一是使用classmethod。 但是,使用此功能,我在代码重用和模块化方面遇到了问题。 这是一个示例,其中我可以基于提供的文件或通过其他方式创建对象:

class Image:

    def __init__(self, filename):
         self.image = lib.load(filename)
         self.init_others()

    @classmethod
    def from_data(cls, data, header):
        cls.image = lib.from_data(data, header)
        cls.init_others()
        return cos

    def init_others(self):
        # initialise some other variables
        self.something = numpy.matrix(4,4)

现在看来我做不到。 cls.init_others()调用失败,因为我没有提供调用它的对象。 我想我可以在from_data函数本身中初始化东西,但是然后我在init方法和其他“构造函数”中重复代码。 有谁知道我如何从这些@classmethod标记的函数中调用这些其他初始化方法? 或者,也许有人知道初始化这些变量的更好方法。

我来自C ++背景。 因此,仍然尝试在python构造中找到自己的方式。

我建议不要尝试创建多个构造函数,而应使用关键字参数:

class Image(object):
    def __init__(self, filename=None, data=None, header=None):
         if filename is not None:
             self.image = lib.load(filename)
         elif data is not None and header is not None:
             self.image = lib.from_data(data, header)
         else:
             raise ValueError("You must provide filename or both data and header")
         self.init_others()

    def init_others(self):
        # initialise some other variables
        self.something = numpy.matrix(4,4)

这是处理这种情况的一种更Python化的方法。

您的类方法应创建并返回该类的新实例,而不是分配类属性并返回该类本身。 作为关键字参数的替代方法,您可以执行以下操作:

class Image:

    def __init__(self, image):
        self.image = image
        self.init_others()

    @classmethod
    def from_data(cls, data, header):
        return cls(lib.from_data(data, header))

    @classmethod
    def from_filename(cls, filename):
        return cls(lib.load(filename))

    def init_others(self):
        # initialise some other variables
        self.something = numpy.matrix(4, 4)

如果您已经有image ,这将增加创建实例的能力。

您应该始终将self作为第一个参数传递给将对类实例起作用的任何方法。 除非您这样做,Python不会自动确定您要为其尝试调用该方法的实例。 因此,如果您想使用类似

the_image = Image("file.txt")
the_image.interpolate(foo,bar)

您需要在Image中将方法定义为

def interpolate(self,foo,bar):
  # Your code

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM