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))
2 Answers 2
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.
3 Comments
re.match which does the same thing as re.search(r'^...') ?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 atuple, which you should perhaps take a look at. - Calling the object
selfis 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.
3 Comments
Range.range.range is not a keyword, and yes, I understood that part. One important point is that types should be UpperCase while functions like range() should be lower_case. Accidentally overwriting functions (id and list are classics there) could not have happened then. I believe that PEP 8 also talks about this issue.
__get__of methods. It's stupid and helps nothing, but it's not like it's impossible.