LPTHW - Day 185 You Make A Game

There are no Day 146 till Day 184.

Wow, almost 40 days since I last worked on the  LPTHW  , I have to reread back all my notes to refresh my memory again. Note to self: No matter how busy you are, if you are discipline enough, surely you will find some time everyday (15 minutes) to do something with the exercise.

Zed is currently revising the LPTHW book especially exercises 40 till 45. All my write-up are based on version 2.0 of the book. You should be able to find a version of the book if you google hard enough.

Continue with exercise 43 of LPtHW. This main focus of the exercise is to rewrite all the function in exercise 42 into classes. I learned that the reason why I stucked at this exercise last time I can't remember that almost everything is an object in python.

Classes in Python cannot be instantiated using a string name.  Again, I forget that Python is not PHP. Variable variables simply does not work in Python. Let's try some examples to illustrate this.

a) Check a name is defined in the namespace
>>> klass
Traceback (most recent call last):
File "<stdin>", line 1, in 
NameError: name 'klass' is not defined

b) Create a sample class
>>> class klass:
    pass

c) The name klass is defined.
>>> klass
<class __main__.klass at 0x7fa690a14598">

d) Create an instance of the klass.
>>> k = klass()
>>> k
<__main__ .klass="" 0x7fa690a19ea8="" at="" instance="">

e) Print and show the type of the string of 'klass'.
>>> 'klass'
'klass'
>>> type('klass')


f) Display the type of the klass instance.
>>> type(klass)


g) Reason why we can't simply instantiate a string name.
>>> k = 'klass'()
Traceback (most recent call last):
File "", line 1, in 
TypeError: 'str' object is not callable

No comments:

Post a Comment