Changing the private variables content

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Wed Jul 22 09:28:23 EDT 2009


On Wed, 22 Jul 2009 14:29:20 +0200, Ryniek90 wrote:

> When i use this class in Python IDLE, i've got this error: "
...
> Traceback (most recent call last):
>   File "<pyshell#60>", line 1, in <module>
>     mod.print_module('socket')
>   File "<pyshell#57>", line 48, in print_module
>     module_open = open(self._this_module, 'rb')
> IOError: [Errno 2] No such file or directory: ''
>  >>>
> "
> 
> As You can see, i can't assign the new value "os.path.join(root, f)" to
> the 'self._this_module variable'.

In the __init__ method, you successfully set the `_this_module` attribute:

        self._this_module = ''

That works, so it proves that you *can* set a private attribute.

Later on, you call the `_SetVar` method, which does this:

    def _SetVar(self, attr, val):
        self.attr = val   

In English, this method does this:

(1) Take two arguments, and store them in variables called "attr" and 
"val".

(2) Assign the value stored in "val" to an attribute named exactly "attr".

What you actually want is:

(1) Take two arguments, and store them in variables called "attr" and 
"val".

(2) Assign the value stored in "val" to an attribute with the name stored 
in the variable "attr".

Can you see the difference?

What you actually want is:

    def _SetVar(self, attr, val):
        setattr(self, attr, val)


Your code is terribly complicated. This will probably do what you want. 
(Warning -- I haven't tested it, so there may be a few errors.)


class ModPrint(object):
    u"""
    This will be the doc.
    """
    def __init__(self, default_search_path=''):
        self.default_search_path = ''

   def find_module(self, modulename, search_path=''):
       if search_path == '':
           # Try the default search path instead.
           search_path = self.default_search_path
        if search_path == '':  # still blank.
            # Try the Python search path instead.
           search_path = sys.exec_prefix
        for root, dirs, files in os.walk(search_path):
            for f in files:
                if f == "%s.py" % modulename:
                    return os.path.join(root, f)

    def get_module_text(self, modulename, search_path=''):
        filename = self.find_module(modulename, search_path)
        module_open = open(filename, 'rb')
        module_text = module_open.read()
        module_open.close()
        return module_text


I changed the name of print_module_text because it doesn't actually print 
anything.



-- 
Steven



More information about the Python-list mailing list