ted
ted

Reputation: 4985

python create method object for string.Method

I have a class which outputs a lot of textchunks, depending on an initial parameter I want it to justify the text right/left/center. I was wondering if it is possible to use a method object (http://docs.python.org/py3k/tutorial/classes.html#method-objects) instead of a function like

class textOutput(object):
    def __init__(self):
        self.justification = "left"

    def justify(self,text):
        if self.justification == "right":
            return text.rjust(self._width)
        elif self.justification == "center":
            return text.center(self._width)
        else:
            return text.ljust(self._width)

    def output(self):
        for i in range(1 to 1000000):
            print self.justify(i)

i would like to use a function object like this (replaceing the justify method above)

class textOutput(object):
    def __init__(self):
        self.justify = string.ljust

    def output(self):
        for i in range(1 to 1000000):
            print self.justify(i,self._width)

    def setJustification(self, justification):
        if justification == "right":
            self.justify = string.rjust
        elif justification == "center":
            self.justify = string.center
        else:
            self.justify = string.ljust

however I do not know i get functionobjects for the string-datatype members.

How can I achieve the later? (The former has so many unneccessary checks going against performance)

p.s.: I have to use jython which is basically python 2.5

p.p.s.: The justification switching would then be done witht he following class method:

Upvotes: 0

Views: 217

Answers (2)

Hari G
Hari G

Reputation: 5

I hope you looked at getattr method to grab the function object from string. The following line in your code should get ur stuff working

{ self.justify = getattr(' ', 'ljust', None)}

Upvotes: 0

David Robinson
David Robinson

Reputation: 78620

You can either do

import string

at the beginning of the file, or use

str.ljust
str.rjust
str.center

instead of the corresponding usages of string. Also, you don't call setJustification in the current code.

Upvotes: 1

Related Questions