python 如何限制类的示例访问某些方法?

wnvonmuf  于 9个月前  发布在  Python
关注(0)|答案(1)|浏览(60)

我目前有一个类,它有几个属性和方法。我想实现一个用于特殊情况初始化的伪替代构造函数。我计划使用https://stackoverflow.com/a/682545中描述的方法。
这是我想做的事情的框架:

class MyClass:
  def __init__(self, input1, input2....)
    # init the class
  @classmethod
  def alt_ctor(cls, input):
    return cls...

  def method1(self):
    # do something

  def method2(self):
    # do something

  def method3(self):
    # do something

对于使用alt_ctor创建的示例,我只想给予它对method2的访问权,而不想赋予它对其他方法的访问权。
在Python中有没有简单的方法可以做到这一点?我知道的唯一方法是让alt_ctor读入一些标志并将其存储为示例属性,然后针对每个方法的该标志进行Assert。

4nkexdtk

4nkexdtk1#

你应该有两个独立的类,而不是一个有替代构造函数的类:

class MyClassLimited:
    def __init__(self, input):
        # ...

    def method2(self):
        # ...

class MyClass(MyClassLimited):
    def __init__(self, input1, input2, input3):
        input = # ...
        super().__init__(input)
        # ...

    def method1(self):
        # ...

    def method3(self):
        # ...

相关问题