Python Forum
Mix-in class tree file not running the self test code.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Mix-in class tree file not running the self test code.
#4
Hey Retribution,

Sorry to bug you again but, I corrected the line 51 to self.__class__.__name__.
Unfortunately I am getting a subsequent error which is as follows;
Please let me know where did I screw up this time.

#!python
# File: listtree.py (2.X + 3.X)


class ListTree:
    """
    Mix-in that returns an __str__ trace of the entire class tree and all
    its objects' attrs at and above self; run by print(), str() returns
    constructed string; uses __X attr names to avoid impacting clients;
    recurses to superclasses explicitly, uses str.format()for clarity;
    """

    def __attrnames(self, obj, indent):
        spaces = ' ' * (indent+ 1)
        result = ''
        for attr in sorted(obj.__dict__):
            if attr.startswith('__') and attr.endswith('__'):
                result += spaces + '{0}\n'.format(attr)
            else:
                result += spaces + '{0}={1}\n'.format(attr, getattr(obj, attr))
                #result += spaces + '%s=%s\n' % (attr, getattr(obj, attr))
        return result


    def __listclass(self, aClass, indent):
        dots = '.' * indent
        if aClass in self.__visited:
            return '\n{0}<Class {1}:, address {2}: (see above)>\n'.format(
                            dots,
                            aClass.__name__,
                            id(aClass))
        
        else:
            self.__visited[aClass] = True
            here  = self.__attrnames(aClass, indent)
            above = ''
            for super in aClass.__bases__:
                above += self.__listclass(super, indent+4)
            return '\n{0}<Class {1}, address {2}: \n{3}{4}{5}>\n'.format(
                            dots,
                            aClass.__name__,
                            id(aClass),
                            here, above,
                            dots)


    def __str__(self):
        self.__visited = {}
        here  = self.__attrnames(self, 0)
        above = self.__listclass(self.__class__, 4)
        return '<Instance of {0}, address {1}:\n{2]{3}>'.format(
                            self.__class__.__name__,
                            id(self),
                            here, above)


if __name__ == '__main__':
    import testmixin
    testmixin.tester(ListTree)

                    
#!python
# File: testmixin.py (2.X + 3.X)

"""
Generic lister mixin tester: similar to transitive reloader in
Chapter 25, but passes a class object to tester (not function),
and testbyNames adds loading of both module and class by name
string here, in keeping with Chapter 31's factory pattern.
"""

import importlib



def tester(listerclass, sept=False):
    


    class Super:
        def __init__(self):                             # Superclass __init__
            self.data1 = 'spam'                         # Create instance attrs
        def ham(self):
            pass


    class Sub(Super, listerclass):                      # Mix in ham and a __str__
        def __init__(self):                             # Listers have access to self
            Super.__init__(self)
            self.data2 = 'eggs'                         # More instance attrs
            self.data3 = 42
        def spam(self):                                 # Define another method here
            pass


    instance = Sub()                                    # Return instance with lister's __str__
    print(instance)                                     # Run mixed-in __str__ (or via str(x))
    if sept:
        print('-' * 80)



def testbyNames(modname, classname, sept=False):
    modobject   = importlib.import_module(modname)      # Import by namestring
    listerclass = getattr(modobject, classname)         # Fetch attr by name string
    tester(listerclass, sept)



if __name__ == '__main__':
    testbyNames('listinstance', 'ListInstance', True)   # Test all three here
    testbyNames('listinherited', 'ListInherited', True)
    testbyNames('listtree', 'ListTree', False)
    
Error:
Traceback (most recent call last): File "C:\Users\Ganga Mohan\AppData\Local\Programs\Python\Python36-32\listtree.py", line 59, in <module> testmixin.tester(ListTree) File "C:\Users\Ganga Mohan\AppData\Local\Programs\Python\Python36-32\testmixin.py", line 36, in tester print(instance) # Run mixed-in __str__ (or via str(x)) File "C:\Users\Ganga Mohan\AppData\Local\Programs\Python\Python36-32\listtree.py", line 54, in __str__ here, above) ValueError: unexpected '{' in field name
Reply


Messages In This Thread
RE: Mix-in class tree file not running the self test code. - by arjunsingh2908 - Aug-14-2018, 05:46 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  problem in running a code akbarza 7 541 Feb-14-2024, 02:57 PM
Last Post: snippsat
  super() and order of running method in class inheritance akbarza 7 594 Feb-04-2024, 09:35 AM
Last Post: Gribouillis
  Class test : good way to split methods into several files paul18fr 4 402 Jan-30-2024, 11:46 AM
Last Post: Pedroski55
  writing and running code in vscode without saving it akbarza 1 344 Jan-11-2024, 02:59 PM
Last Post: deanhystad
  the order of running code in a decorator function akbarza 2 478 Nov-10-2023, 08:09 AM
Last Post: akbarza
  error "cannot identify image file" part way through running hatflyer 0 612 Nov-02-2023, 11:45 PM
Last Post: hatflyer
  Python Code for Preorder Traversal of a Binary Tree Bolt 1 554 Sep-22-2023, 09:32 AM
Last Post: Gribouillis
  unittest generates multiple files for each of my test case, how do I change to 1 file zsousa 0 918 Feb-15-2023, 05:34 PM
Last Post: zsousa
  "Name is not defined" when running a class lil_e 6 3,758 Jan-12-2023, 11:57 PM
Last Post: lil_e
  Web project and running a .py file emont 0 619 Dec-11-2022, 11:15 PM
Last Post: emont

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020