Jean
Jean

Reputation: 22675

Implicit self in Python

In Python, to reduce clutter, is there a way to "Declare" members/methods of a class as "self" or a workaround.

class range:
    #range_start # Declare as self
    #range_end   # Declare as self

    def __init__(self,my_range_start,my_range_end):
        range_start = my_range_start
        range_end   = my_range_end

    def print_range(self):
        print ("%x %x" % (range_start,range_end))

Upvotes: 0

Views: 567

Answers (2)

Ulrich Eckhardt
Ulrich Eckhardt

Reputation: 17415

You can not achieve what you ask for in the way that you want, the idea of implicit self has been discussed and discarded by the python community.

However, concerning your code example, you can reduce the amount of code:

class range(tuple):
    def print_range(self):
        print("%x %x" % self)

Still, that code is bad, because adding a print_range() function is the wrong approach (why is it called print_range() and not print(), btw?). Instead, provide implementations of __str__() and __repr__() to format the object.

Some more notes:

  • There is a namedtuple() function that creates a type similar to a tuple, which you should perhaps take a look at.
  • Calling the object self is a convention, you can name it anything you like. Others won't easily be able to read your code though.
  • Concerning style, check out PEP 8. There is a bunch of conventions that you should adhere to, unless you have a good reason not to.

Upvotes: 2

Noufal Ibrahim
Noufal Ibrahim

Reputation: 72735

There isn't any straightforward way to do this. Also, if you did, you'd violate some rather deep set python conventions and your code would become much harder to read for other Python programmers. Too high a cost, in my opinion, to reduce visual clutter.

Upvotes: 5

Related Questions