Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python3:在实例化类之前从类中删除属性_Python_Python 3.x_Python Decorators - Fatal编程技术网

Python3:在实例化类之前从类中删除属性

Python3:在实例化类之前从类中删除属性,python,python-3.x,python-decorators,Python,Python 3.x,Python Decorators,我正在使用Python3,我有一个非常重的类,它有许多函数作为属性: Class A (object): def __init__(self): ... def method1(self): ... def method2(self): ... ... def methodN(self): ... 例如,我想创建一个只有method1的类A实例。我怎么能这样做 使用继承,

我正在使用Python3,我有一个非常重的类,它有许多函数作为属性:

Class A (object):

    def __init__(self):
        ...

    def method1(self):
        ...

    def method2(self):
        ...


        ...

    def methodN(self):
        ...
例如,我想创建一个只有
method1
的类A实例。我怎么能这样做

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


我考虑过在调用
\uuuu init\uuuu
之前装饰类并删除其属性,但我甚至不确定从何处着手解决这个问题。有什么想法吗?

您可以修改类的
\uuuu getattribute\uuuu
方法,以禁止访问这些属性(通过普通
实例.attribute
访问)

A类(对象):
定义初始化(self,x):
self.x=x
def方法1(自身):
...
def方法2(自身):
...
def uu getattribute_uu(self,name):
if对象。获取属性(self,'x'):
如果名称==“method2”:
raise AttributeError(“无法访问method2为self.x为True”)
返回对象。\uuuGetAttribute(self,name)
>>>a=a(假)
>>>a.方法1
>>>a.方法2
>>>b=A(真)
>>>方法1
>>>方法2
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“”,第11行,在__
AttributeError:无法访问method2为self。x为True

显然,这会变得相当笨拙,并且违反了关于类的实例意味着什么的许多假设。我想不出一个好的理由在真实代码中这样做,因为您仍然可以通过
对象访问方法。\uuuu getattribute\uuub(method2')

为什么要这样做?@kaya3我想这样做,因为原始类非常繁重,其中包含大量函数。它的使用方式很好,但是出现了一个新的用例,我们需要从另一个端点调用它,只需要使用它的一个或两个方法(这些方法每次都不同,并指定为参数)。您是否有这样的印象,即在创建实例时,这些方法会复制到实例中?事实并非如此。你的意思是,一个包含100个方法的
类A
实例将占用与一个包含一个方法的
类B
实例(所有方法都相同)相同的内存吗?是的,没错。这两种方法都只保留了对它们的
\uuuuuu class\uuuuuu
属性的引用,并在该属性上查找方法。您可以使用
sys.getsizeof
进行测试。
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