python - How to enforce method signature for child classes? -


Text after "itemprop =" text ">

Like the C # quote, the Java method is loaded, if the child class does not apply the method with exact signature overwrite Will not, which means the basic method.

How do we apply the method signature in child classes in Python? The following code sample shows that the child class overwrites the original method with different method signatures:

  & gt; & Gt; & Gt; Class A (Object): ... Diff Me (Self, P = None): ... Enhance Customized Arrays ('Not applicable') ... & gt; & Gt; & Gt; Class B (A): ... Diff Me (self, p 2 = none): ... print P2 ... & gt; & Gt; & Gt; B () M ('123') 123   

Although it is not very important, or it may be that the design of a dragon (like * args, ** quorz) I am asking for clarity if this is possible.

Please note:

I have tried @ abstractmethod and ABC already.

Below is a full-fledged example, to ensure that how to use metaLessels sub -School methods have the same signature as the base classes. Use the Inspection module to note the way I am using it here to ensure that signing is actually One can not be what you want. Inspection class of BadSignatureException (makes an exception): Pass class SignatureCheckerMeta (type): def __new __ (CLS, name, baseClasses, d): For each method #For, d Also the base class is a way of trying to check that name #defined. If so, make sure that # signatures are the same for the methodName in D: f = D [methodName] for baseClass in baseClasses: try: fBase = getattr (baseClass, methodName) .___fancc__ not inspect.getargspec (f) ) == inspect.getargspec (fBase): Enhanced BadSignatureException (STR (MethodName)) except for AttributeError: # This method is not defined in this base class, # Then just go to the next base class to continue the return type (Name, baseClasses, d) DEF main (): class one (object): def foo (self, x): passed try: that Star B (A): __metaclass__ = SignatureCheckerMeta DEF foo (self): "" "This override should not work because the signature is wrong" "BadSignatureException: print (" Class B can not be made due to poor signature signature) Try "Except" ("this is as it should be :)") Try: Class C (A): __metaclass__ = SignatureCheckerMeta def foo (self, x): "" except BadSignatureException passed "" "because the signature matches A.foo is okay ":. Print ("Class C could not be created, something went wrong") If __name__ == "__main__": main ()

Comments

Popular posts from this blog

Java - Error: no suitable method found for add(int, java.lang.String) -

java - JPA TypedQuery: Parameter value element did not match expected type -

c++ - static template member variable has internal linkage but is not defined -