【问题标题】:Python 3: remove attributes from class before instancing itPython 3:在实例化之前从类中删除属性
【发布时间】:2020-06-02 19:54:34
【问题描述】:

我正在使用 Python3,并且我有一个非常重的类,其中包含许多函数作为属性:

Class A (object):

    def __init__(self):
        ...

    def method1(self):
        ...

    def method2(self):
        ...


        ...

    def methodN(self):
        ...

例如,我想创建一个只有 method1 的类 A 的实例。我怎么能这样做?

使用继承,虽然它可能是技术上最正确的方法,但在我的情况下不是一个选择 - 我不能对代码库进行太多修改。

我想过在调用__init__ 之前装饰类并删除它的属性,但我什至不知道从哪里开始解决这个问题。有什么想法吗?

【问题讨论】:

  • 你为什么要这样做?
  • @kaya3 我想这样做是因为原来的类很重,里面有这么多的函数。它的使用方式运行良好,但是出现了一个新的用例,我们需要从另一个端点调用它,只需要使用它的一个或两个方法(这些方法每次都会不同并指定为参数) .
  • 您是否觉得创建实例时方法会被复制到实例中?事实并非如此。
  • 您的意思是class A 的实例有一百个方法会占用与class B 的实例只有一个方法(所有方法相同)一样多的内存吗?跨度>
  • 是的,完全正确。两者都只是引用了他们的__class__ 属性,并在上面查找方法。您可以使用sys.getsizeof 进行测试。

标签: python python-3.x python-decorators


【解决方案1】:

您可以修改该类的__getattribute__ 方法以禁止访问这些属性(通过普通instance.attribute 访问)

class A (object):
    def __init__(self, x):
        self.x = x
    def method1(self):
        ...
    def method2(self):
        ...
    def __getattribute__(self, name):
        if object.__getattribute__(self, 'x'):
            if name == 'method2':
                raise AttributeError("Cannot access method2 is self.x is True")
        return object.__getattribute__(self, name)

>>> a = A(False)
>>> a.method1
<bound method A.method1 of <__main__.A object at 0x000001E25992F248>>
>>> a.method2
<bound method A.method2 of <__main__.A object at 0x000001E25992F248>>
>>> b = A(True)
>>> b.method1
<bound method A.method1 of <__main__.A object at 0x000001E25992F2C8>>
>>> b.method2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 11, in __getattribute__
AttributeError: Cannot access method2 is self.x is True

显然,这变得非常笨拙,并且违反了许多关于作为类的实例意味着什么的假设。我想不出在实际代码中执行此操作的充分理由,因为您仍然可以通过 object.__getattribute__(b, 'method2') 访问这些方法

【讨论】:

    猜你喜欢
    • 2015-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-28
    • 1970-01-01
    相关资源
    最近更新 更多