Nohl
Nohl

Reputation: 33

Python - How use properties without creating an object

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

Answers (2)

pzp
pzp

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:

  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!

Upvotes: 0

vaultah
vaultah

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

Related Questions