Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

inheritance - Non-inheritable method in python

Suppose I have two classes, one inheriting from the other :

class A():
    def __init__(self):
        pass

    def doSomething(self):
        print('It Works !') # Insert actual code here

class B(A):
    pass

How do I make the doSomething method impossible to inherit, so that : ( I want to make the error happen )

>>> a = A()
>>> a.doSomething()
'It Works !'
>>> b = B()
>>> b.doSomething()
Traceback (most recent call last):
  File "<pyshell#132>", line 1, in <module>
    b.doSomething()
AttributeError: 'B' object has no attribute 'doSomething'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should question whether you want to have a non-inheritable part in the first place. It would be more typical to abstract out the common parts of A and B into a common parent, or use a mixin pattern.

    class Parent
     def doCommonThing1
     def doCommonThing2
     /          
    /            
   /              
  /                
class A            class B
 def doSomething    def doOtherThing

If you insist that B must be a subclass of A, then the only way to "uninherit" a method is to override it to do something else. For example, a property which raises attribute error is for all practical purposes the same as a missing attribute:

>>> class A:
...     def doSomething(self):
...         print("it works")
... 
>>> class B(A):
...     @property
...     def doSomething(self):
...         msg = "{!r} object has no attribute 'doSomething'"
...         raise AttributeError(msg.format(type(self).__name__))
... 
>>> A().doSomething()
it works
>>> hasattr(B(), "doSomething")
False
>>> B().doSomething()
...
AttributeError: 'B' object has no attribute 'doSomething'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...