[Classless] Just to be sure...

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Yermat

    [Classless] Just to be sure...

    Hi all,
    I just want to be sure that I have really understand what classless
    means... Can you look at the following "test" function and tell me if
    this is what you would have called classless programmation ?

    thanks !
    --
    Yermat


    import types

    PropertyType = type(property() )

    class Prototype(objec t):
    parent = None
    def __init__(self, parent=None):
    self.parent = parent

    def clone(self):
    return Prototype(self)

    def __hasattr__(sel f, name):
    if name in self.__dict__:
    return True
    elif self.parent!= None:
    return self.parent.__h asattr__(self, name)
    else:
    return False

    def __getattribute_ _(self, name):
    if name in ['__dict__', 'parent']:
    return object.__getatt ribute__(self, name)
    if name in self.__dict__:
    val = self.__dict__[name]
    elif self.parent != None:
    val = getattr(self.pa rent, name)
    else:
    val = object.__getatt ribute__(self, name)
    if type(val) in [types.FunctionT ype, types.Generator Type,
    types.UnboundMe thodType, types.BuiltinFu nctionType]:
    return val.__get__(sel f, self.__class__)
    if type(val) == PropertyType:
    return val.fget(self)
    return val

    def __setattr__(sel f, name, value):
    if type(value) == types.MethodTyp e:
    value = value.im_func
    self.__dict__[name] = value

    def __add__(self, other):
    return self.__add__(ot her)

    def test():
    import random

    def show(self):
    print '(%s, %s)' % (self.x, self.y)

    def addPoint(self, other):
    r = self.clone()
    r.x = self.x + other.x
    r.y = self.y + other.y
    return r

    point = Prototype()
    point.show = show
    point.__add__ = addPoint

    a1 = point.clone()
    a1.x = 3
    a1.y = 5

    a2 = point.clone()
    a2.x = 7
    a2.y = 9

    print 'a1: ',
    a1.show()
    print 'a2: ',
    a2.show()


    def getX(self):
    return random.randint( 0, 10)

    print 'a3:'
    a3 = a2.clone()
    a3.x = property(getX)

    print a3.x
    a3.show()
    a3.show()
    a3.show()

    a2.y = 10
    print 'a3: ',
    a3.show()

    p = a3.__add__(a2)
    print 'p = a3 + a2: ',
    p.show()

    print 'a3 + a2: ',
    (a3 + a2).show()

    def squareDistance( self):
    return (self.x ** 2) + (self.y ** 2)

    point.squareDis tance = squareDistance

    a4 = a1.clone()
    print 'a4: ',
    a4.show()
    print a4.squareDistan ce()

    def pointTuple(self ):
    return (self.x, self.y)

    a5 = a3.clone()
    a5.tuple = pointTuple
    print 'a5: ', a5.tuple()
    a5.x = 10
    print 'a5: ', a5.tuple()
    print 'a3: ',
    a3.show()

    if __name__=='__ma in__':
    test()

Working...