Steven D'Aprano wrote:
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.



Moreover, if I'm not wrong there is absolutely no difference in the way python is handling private and public attributes, for python, both are the same kind of attributes. This is purely conventional (some doc processing tool will take into account the private prefix).

So there is absolutely no restriction in writing self._myVar = 0 in any of the instance methods.

JM

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to