"object" vs "dynamic" programming styles

Edward C. Jones edcjones at erols.com
Sat Mar 24 22:28:30 CET 2001


Here are three methods for doing the same thing. When is it better to use
one of the approaches rather than another?

=============================================================
# Program 1:

# The constructor X(c) actually creates an A or B instance.
class X:
    def __init__(self, c):
        self.whoami = 'X'
        self.Xs = 'Xs'
        if c == 'a':
            self.__class__ = A
            A.__init__(self)
        elif c == 'b':
            self.__class__ = B
            B.__init__(self)

    def fun(self):
        print 'X.fun called'

class A(X):
    def __init__(self):
        X.__init__(self, '')
        self.whoami = 'A'
        self.As = 'As'

    def fun(self):
        print 'A.fun called'

class B(X):
    def __init__(self):
        X.__init__(self, '')
        self.whoami = 'B'
        self.Bs = 'Bs'

a = X('a')
print 'a.__class__:', a.__class__
print 'a.whoami:', a.whoami
print 'a.Xs:', a.Xs
print 'a.As:', a.As

a.fun()

b = X('b')
b.fun()

===================================================================

# Program 2

# Which attributes X(c) has depends on the value of c.
class X:
    def __init__(self, c):
        self.Xs = 'Xs'
        if c == 'a':
            self.set_A()
        elif c == 'b':
            self.set_B()

    def set_A(self):
        self.whoami = 'A'
        self.As = 'As'
        self.fun = self.fun_A

    def set_B(self):
        self.whoami = 'B'
        self.Bs = 'Bs'

    def fun_A(self):
            print 'A_fun'

a = X('a')
print 'a.__class__:', a.__class__
print 'a.whoami:', a.whoami
print 'a.Xs:', a.Xs
print 'a.As:', a.As

a.fun()

b = X('b')
try:
    b.fun()
except AttributeError, x:
    print x

===================================================================

# Program 3

# The function New_X returns an instance of either class A or class B.
def New_X(c):
    if c == 'a':
        return A()
    if c == 'b':
        return B()

class A:
    def __init__(self):
        self.whoami = 'A'
        self.Xs = 'Xs'
        self.As = 'As'

    def fun(self):
        print 'A.fun called'

class B:
    def __init__(self):
        self.whoami = 'B'
        self.Xs = 'Xs'
        self.Bs = 'Bs'

a = New_X('a')
print 'a.__class__:', a.__class__
print 'a.whoami:', a.whoami
print 'a.Xs:', a.Xs
print 'a.As:', a.As

a.fun()

b = New_X('b')
try:
    b.fun()
except AttributeError, x:
    print x

===================================================================





More information about the Python-list mailing list