0

How do I write a class to make this code work.

class number:

    def double(self):
        return n*2

print(number(44).double)
>> 88

2 Answers 2

4

Well, you could decorate the number.double method with property:

class number:
    def __init__(self, number):
        self.number = number
    @property
    def double(self):
        return self.number * 2


print(number(42).double) # 84

If you know the type of your argument, it'd be better to inherit number from it. For example

class number(int):
    @property
    def double(self):
        return type(self)(self * 2)

print(number(42).double) # 84
print(number(42).double.double) # 168
Sign up to request clarification or add additional context in comments.

3 Comments

Don't know why you're subclassing int when they're seem to be trying to write a generic numeric class.
@L3viathan number('Too generic huh?').double
behaviour seems fine by me! If you don't want that, check for int, float, long, and complex.
0

Here you are:

class Number(object):

    def __init__(self, n):
        self.n = n

    def double(self):
        return 2*self.n

print(Number(44).double())

A couple of notes:

  1. Since double() is a method of the class Number (and not an attribute), you need to use parentheses to call it.
  2. In Python it's considered standard practice to give classes uppercase names.
  3. If you want to define an instance variable (in this case n, or 44, you must def the __init__() function which gives the interpreter instructions for how to create, or initialize an instance of your class.

Hope this helps, and good luck!

2 Comments

I am making an exercise on codewars and I need to use the following syntaxe. I don't think I can use a method. Here is the test case. test.assert_equals(PrimeFactorizer(24).factor, {2: 3, 3: 1})
Do you have the code or documentation for test.assert_equals(). I'm almost positive that test.assert_equals() takes the actual function as an argument (rather than the value returned by calling the function), so that it can call the function itself. If this is so, then PrimeFactorizer.factor() is really a method even though you don't use parentheses when using it that particular way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.