Welcome, guest | Sign In | My Account | Store | Cart

Dummy classes can be used to create dummy instances of class which we can't create currently!

Python, 36 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import sys
class Dummy:
    def __init__(self,identity = 'unknown'):
        self.identity = identity
        self.name = ''

    def call(self,*args):
        method = self.name + "("
        count = 1

        for o in args:
            if count != 1:
                method = method + ","
            method = method + repr(type(o))
            count = count + 1
            
        method = method + ")"
        try:
            raise "Dummy"
        except:
            line = 'Line ' +repr(sys.exc_info()[2].tb_frame.f_back.f_lineno)+': '
        raise AttributeError(line + method+" called on dummy "+self.identity+" Object\n")
        
    def __getattr__(self, name):
        self.name = name
        return self.call

if __name__ == '__main__':
    try:
        rect = ''
        rect = Dummy('Rectangle')#try also after commenting this line
        rect.GetWidth()
        rect.SetHeight(50)
        rect.SetColor('Red')
    except AttributeError,e:
        print e

sometimes we don't have enough information to create a class instance usually in that case programmers tend to use simple string assignment e.g rect = '' #which should actually be a class Rectangle object in these cases better approach can be to use Dummy class desribed here as it gives much better information when by mistake functions are called for that object try to tun this code

Created by anurag uniyal on Mon, 27 Aug 2001 (PSF)
Python recipes (4591)
anurag uniyal's recipes (12)

Required Modules

Other Information and Tasks