Differences between revisions 1 and 2
Revision 1 as of 2005-12-21 22:10:40
Size: 1816
Editor: 204
Comment:
Revision 2 as of 2005-12-21 22:11:52
Size: 1831
Editor: 204
Comment:
Deletions are marked like this. Additions are marked like this.
Line 16: Line 16:
=== Edit Title === === Sample (copy and edit me) ===

Here are some short examples that have provided unexpected results for intermediate-level Python programmers.

Add new examples by copying and editing the following sample. Edit your code so it is short and does nothing more than illustrate your problem. Often programming problems are solved by making the effort to create simple examples that reproduce them. This page is meant for problems that appear in a few lines of code after the extraneous fluff has been removed. Things that may appear normal to experienced Python programmers but appear weird: at least when one first encounters them.

If you can answer your own question, do so. Otherwise leave the answer part for somebody else to edit.

Sample (copy and edit me)

Bold

print "edit this"

Usage

>>> edit this

Question

Edit this question.

Answer

Edit this answer.

Metaclass Instantiation

Bold

class A(object):
    
    def __init__(self):
        self.__setattr__('x',1)
        
a = A()

class M(type):
    
    def __init__(cls,cls_name,bases,cls_dict):
        super(M,cls).__init__(cls_name,bases,cls_dict)
        cls.__setattr__('y',1)

class B:
    __metaclass__ = M
    pass

Usage

>>> import Play
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "Play.py", line 14, in ?
    class B:
  File "Play.py", line 12, in __init__
    cls.__setattr__('y',1)
TypeError: Error when calling the metaclass bases
     expected 2 arguments, got 1

Question

I thought creating the class B was analogous to creatig the object a. Clearly, my use of setattr has stretched the analogy too far but ... I don't know what's going on.

Answer

Edit this answer.

Intermediate Conundrums (last edited 2019-10-19 21:39:39 by FrancesHocutt)

Unable to edit the page? See the FrontPage for instructions.