Coding Style: Defining Functions within Methods?

Anton Vredegoor anton at vredegoor.doge.nl
Fri Sep 5 20:21:15 EDT 2003


 harry.pehkonen at hotpop.com (Harry Pehkonen) wrote:

>I have been defining new class methods when I'm trying to simplify
>some code.  But I'm thinking I should just define functions within
>that method because they aren't useful from the outside anyway. 

It's also possible to generate classes by using a factory function.
For an example of it getting a bit out of control see the code below.

Anton

---

from __future__ import division
from Tkinter import *

def template(x=None):
    class T(tuple):
        def __new__(cls, *args):
            return tuple.__new__(cls, args)
        def geta(self): return self[0]
        def getb(self): return self[1]
        a,b = map(property,[geta,getb])
    return T
    
Point = template()
Rect = template(Point)
Cube = template(Rect)

class Transformer(Cube):
    
    def __init__(self, *args):
        a,b = self.a,self.b
        fx = (b.b.a-b.a.a)/(a.b.a-a.a.a)
        fy = (b.b.b-b.a.b)/(a.b.b-a.a.b)
        f = min(fx,fy)
        wxc = (a.a.a+a.b.a)/2
        wyc = (a.a.b+a.b.b)/2
        vxc = (b.a.a+b.b.a)/2
        vyc = (b.a.b+b.b.b)/2
        xc = vxc-f*wxc
        yc = vyc-f*wyc
        self.f,self.xc,self.yc = f,xc,yc

    def transform(self, R):
        f,xc,yc = self.f,self.xc,self.yc
        p1 = Point(f*R.a.a+xc, f*R.a.b+yc)
        p2 = Point(f*R.b.a+xc, f*R.b.b+yc)
        return Rect(p1,p2)

class Cartesian:

    def __init__(self, master):
        self.canvas = Canvas(master,width=500,height=500)
        self.canvas.pack(fill= BOTH, expand=YES)
        master.bind("<Escape>", lambda event='ignored',
            m=master: m.destroy())
        master.bind("<Configure>", self.configure)
   
    def configure(self, event):
        self.draw()

    def draw(self):
        c = self.canvas
        c.delete('all')
        T = Transformer(self.b,self.a)
        colors ='Red Green Blue Magenta Cyan Yellow'.split()
        for i in range(50,0,-1):
            R = Rect(Point(-i,-i),Point(i,i))
            c.create_rectangle(T.transform(R),
                fill=colors[(i-1)%len(colors)])
 
    def geta(self):
        c = self.canvas
        p1 = Point(0,0)
        p2 = Point(c.winfo_width(), c.winfo_height())
        return Rect(p1,p2)
    
    def getb(self):
        a = 50
        p1 = Point(-a,-a)
        p2 = Point(a,a)
        return Rect(p1,p2)

    a,b = map(property,[geta,getb])

def main():
    root = Tk()
    ca = Cartesian(root)
    root.mainloop()

if __name__=='__main__':
    main()









More information about the Python-list mailing list