1

I have a simple problem that I can solve, but I'd like to find a cleaner way to get to my point. Let me give an example:

class Example(object):

    def __init__(self, number):
        self.number = number
        self.constant = 4.0

    def mult(self):
        return self.number * self.constant

So, I have a bound method to my class that is called mult. My problem is I would like to get the self.constant out of the __init__ part of the class as it would be independent from any instance of that class. I was thinking about something like:

class Example(object):

    constant = 4.0

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

    def mult(self):
        return self.number * constant

which obviously doesn't work. I was reading lately on class methods, which appeared like a good hint, but the problem I get with that is that I can't refer to my self.number in my method.

Anybody with a good idea, beside fixing my mult method to return self.number * 4.0 (my real problem is a bit more complex than that).

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Eric B
  • 1,635
  • 4
  • 13
  • 27
  • 1
    **TL;DR**: you still have to access class attributes on the instance (`self.constant`) or class (`Example.constant`). – jonrsharpe Aug 05 '17 at 14:18

0 Answers0