如何隐藏/删除Python中继承类中的一些方法?

时间:2014-04-20 11:24:21

标签: python

希望在class B的继承class A期间隐藏一些公开方法

class A(object):
  def someMethodToHide():
    pass

  def someMethodToShow():
    pass

class B(A):
  pass

len(set(dir(A)) - set(dir(B))) == 1

如果可能的话,如何在python中完成?

3 个答案:

答案 0 :(得分:3)

塞尔丘克的suggestion是最好的,但有时候重构太麻烦了。

所以相反,这会让你的同事像女妖一样尖叫并诅咒你的名字。

通过使用元类hide_meta来添加重载的__getattribute____dir__方法。只需设置__metaclass__ = hide_meta__excluded__ = ["list", "of", "unwanted", "attributes/methods"]即可将其应用于所需的课程。

class hide_meta(type):
    def __new__(cls, cls_name, cls_bases, cls_dict):
        cls_dict.setdefault("__excluded__", [])
        out_cls = super(hide_meta, cls).__new__(cls, cls_name, cls_bases, cls_dict)

        def __getattribute__(self, name):
            if name in cls_dict["__excluded__"]:
                raise AttributeError(name)
            else:
                return super(out_cls, self).__getattribute__(name)
        out_cls.__getattribute__ = __getattribute__

        def __dir__(self):
            return sorted((set(dir(out_cls)) | set(self.__dict__.keys())) - set(cls_dict["__excluded__"])) 
        out_cls.__dir__ = __dir__

        return out_cls

class A(object):
    def someMethodToHide(self):
        pass

    def someMethodToShow(self):
        pass

class B(A):
    __metaclass__ = hide_meta
    __excluded__  = ["someMethodToHide"]

a = A()
print dir(a)
b = B()
print dir(b)
b.someMethodToShow()
b.someMethodToHide()

答案 1 :(得分:1)

以下是我评论的答案形式:你可以从第三个类C继承A和B.同样:

class C(object):
  def someMethodToShow():
    pass

class A(C):
  def someMethodToHide():
    pass

class B(C):
  pass

作为旁注,如果您想要的是可能的,那么它将破坏多态性。这个赢了。

答案 2 :(得分:1)

您可以创建一个descriptor类来模拟“已删除”属性。然后,您可以为该类的实例分配“待删除”名称。

这是一个完整的示例,显示了由于对子类及其实例的属性的访问而出现的错误/回溯。通过引发自定义错误,回溯可明确表明该属性已被有意“删除”。

In [1]: class DeletedAttributeError(AttributeError): 
   ...:     pass 
   ...:  
   ...:  
   ...: class DeletedAttribute: 
   ...:     def __set_name__(self, owner, name): 
   ...:         self.name = name 
   ...:  
   ...:     def __get__(self, instance, owner): 
   ...:         cls_name = owner.__name__ 
   ...:         accessed_via = f'type object {cls_name!r}' if instance is None else f'{cls_name!r} object' 
   ...:         raise DeletedAttributeError(f'attribute {self.name!r} of {accessed_via} has been deleted') 
   ...:  
   ...:  
   ...: class Foo: 
   ...:     def hide_me(self): 
   ...:         pass 
   ...:  
   ...:  
   ...: class Bar(Foo): 
   ...:     hide_me = DeletedAttribute() 
   ...:                                                                                       

In [2]: Foo.hide_me                                                                           
Out[2]: <function __main__.Foo.hide_me(self)>

In [3]: Bar.hide_me                                                                           
---------------------------------------------------------------------------
DeletedAttributeError                     Traceback (most recent call last)
<ipython-input-3-240c91cc1fc8> in <module>
----> 1 Bar.hide_me

<ipython-input-1-0f699423deb7> in __get__(self, instance, owner)
     10         cls_name = owner.__name__
     11         accessed_via = f'type object {cls_name!r}' if instance is None else f'{cls_name!r} object'
---> 12         raise DeletedAttributeError(f'attribute {self.name!r} of {accessed_via!r} has been deleted')
     13 
     14 

DeletedAttributeError: attribute 'hide_me' of type object 'Bar' has been deleted

In [4]: Bar().hide_me                                                                         
---------------------------------------------------------------------------
DeletedAttributeError                     Traceback (most recent call last)
<ipython-input-4-9653f0da628c> in <module>
----> 1 Bar().hide_me

<ipython-input-1-0f699423deb7> in __get__(self, instance, owner)
     10         cls_name = owner.__name__
     11         accessed_via = f'type object {cls_name!r}' if instance is None else f'{cls_name!r} object'
---> 12         raise DeletedAttributeError(f'attribute {self.name!r} of {accessed_via!r} has been deleted')
     13 
     14 

DeletedAttributeError: attribute 'hide_me' of 'Bar' object has been deleted

以上代码可在Python 3.6+上运行。