0

Consider a trivial print helper method - that has the intention to reduce typing / clutter for a specifically formatted output structure:

class MyClass(object):

  def p(self, msg,o=None):
    import datetime
    omsg = ": %s" %repr(o) if o is not None else ""
    print("[%s] %s%s\n" %(str(datetime.datetime.now()).split('.')[0], msg, omsg))

The point of making it short/sweet was not to then type

  self.p('Hello world')

But is that the only option?

Note: I want to distribute this class within a small team - and not add a function p() to their namespaces.

WestCoastProjects
  • 58,982
  • 91
  • 316
  • 560
  • There seems to be no reason this `p` method needs to be one - it might as well be a function. In that sense, yes, it is possible. – Kendas Jul 13 '17 at 13:57
  • 1
    You could do `point = self.point` in the scope wherever you're using `self.point`. But honestly, I don't think `self` is that much more to type. – Christian Dean Jul 13 '17 at 13:58
  • You should have a look at this post: https://stackoverflow.com/q/136097/7051394. Besides, the title of your question is a bit misleading: "avoiding the `self` reference" feels like you want to omit `self` as you would omit `this` in Java or most OOP languages, which is not possible in Python. – Right leg Jul 13 '17 at 14:13

1 Answers1

1

If you don't use self anywhere in the method you can decorate it with @staticmethod and omit the self arg

https://docs.python.org/2/library/functions.html#staticmethod

class MyClass(object):

    @staticmethod
    def p(msg, o=None):
        import datetime
        omsg = ": %s" %repr(o) if o is not None else ""
        print("[%s] %s%s\n" %(str(datetime.datetime.now()).split('.')[0], msg, omsg))

You can still call it via self.p(...) from within other methods on instances of the class

You can also call it directly from MyClass.p(...)

Anentropic
  • 32,188
  • 12
  • 99
  • 147