Skip to content
Advertisement

Accept only objects in a method and return new object

I want to create a method that only takes objects of the class it is is defined in, manipulates it and returns a new object of the same class.

For example:

JavaScript

Does anyone have an idea how to get this done? best regards, David

Advertisement

Answer

You can do something like this :

JavaScript

You can add type checking directly in the add function :

JavaScript

If you want to integrate this in the standard fractions module, you can make a class inheriting from fractions.Fraction, which will outpute you a nice irreductible fraction :

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement