Reputation: 33
How do I write a class to make this code work.
class number:
def double(self):
return n*2
print(number(44).double)
>> 88
Upvotes: 0
Views: 255
Reputation: 6617
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:
double()
is a method of the class Number
(and not an attribute), you need to use parentheses to call it.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!
Upvotes: 0
Reputation: 46603
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
Upvotes: 4