#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    14
    Rep Power
    0

    Red face Converting a python code into a python class/module


    Hello,

    Please, I have this python code:

    Code:
    def bugs(species):
            species=str(species)
            url = "dungeonSpear?bugs="
            url += species
            request = urllib2.Request(url, headers={'User-Agent' : "Magic Browser"})
            page = urllib2.urlopen(request)
            soup = BeautifulSoup(page)
            start = time.time()
            parser = etree.HTMLParser()
    	tree   = etree.parse(StringIO.StringIO(html), parser)
            results=[]
            for item in soup.find("div", {"id" : "centralResultDiv"}).findAll("div", "individualWrapper"):
                    title = item.find("div", "searchDtlLeftN").text
                    price= item.find("span", {"class" : "priceR"}).text
                    if (price==""):
                            price="NOT A BUG"
                    #print price[98:115]
                    fineresult= {"title" : title, "price" : price}
                    results.append(individual)
    How do I convert it into a class (a module that can be imported in another python code)?
    I just want to learn how to take this function and make it into a class/module that can be reused in another python code.

    Thanks
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,837
    Rep Power
    480
    Suppose your bugs function is in file

    buggly.py

    To use bugs

    import buggly
    buggly.bugs('Metaltella simoni')


    if...if buggly.py can be found in the directories on your python path.


    What's the python path? The initial value comes from the program environment PYTHONPATH which you can set depending on your command shell.

    Or, you can modify the python path within your program before the import statement.

    import sys
    sys.path.append(r'path/to/the/relevant/directory')


    That's awfully brief. The target file can be a .pyo or .pyc file so you can hide the original python source. I think it can also be a .zip archive now, and you can import a package, which is a directory containing a file that (usually) loads other files. And that file is
    __init__.py
    You should consider this an incomplete overview indicating that you can concoct some elaborate schemes for large projects. Yes, I neglected dynamic libraries.
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    14
    Rep Power
    0
    Originally Posted by b49P23TIvg
    Suppose your bugs function is in file

    buggly.py

    To use bugs

    import buggly
    buggly.bugs('Metaltella simoni')


    if...if buggly.py can be found in the directories on your python path.


    What's the python path? The initial value comes from the program environment PYTHONPATH which you can set depending on your command shell.

    Or, you can modify the python path within your program before the import statement.

    import sys
    sys.path.append(r'path/to/the/relevant/directory')


    That's awfully brief. The target file can be a .pyo or .pyc file so you can hide the original python source. I think it can also be a .zip archive now, and you can import a package, which is a directory containing a file that (usually) loads other files. And that file is
    __init__.py
    You should consider this an incomplete overview indicating that you can concoct some elaborate schemes for large projects. Yes, I neglected dynamic libraries.

    Hello,

    So, I don't need to do anything to the function like :
    class buggly: #making a class out of the function
    def __init__(self, bugs):

    def bugs(species..) #the function..

    ....

    All, I have to do is import the file in which the function is and set the python path to contain that file? How do you use this .pyo files in relation to the file? Am sorry I am new to using python, so if you can explain with an example, that will also help.
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,837
    Rep Power
    480
    python normally compiles sources to .pyc files.
    Invoke python with -o to have it generate .pyo files.
    .pyo are "optimized" which might mean no more than "comments are removed". And you can prevent python from writing .pyc files altogether.

    Classes provide a way to group related data and actions. Here's a ridiculous and too difficult* example class to implement numbers as words. The base class cannot be instantiated by normal means. Provide translation dictionaries to support multiple languages via inheritance. A class constructing factory function simplifies the job. The doctests pass in python3.
    Code:
    '''
        Arithmetic using strings to represent numbers
        Dumb!  But more original that the usual graphics
        objects.  Support multiple languages.
    
        shell_prompt$ python -m doctest this_file.py
    
        >>> a = English()
        >>> a += 'seven'
        >>> print(a - 'two')
        five
        >>> e = English()
        >>> g = German()
        >>> print(g-'eins')
        minus infinity
        >>> print('eins' + g)  # __radd__ invoked
        eins
        >>> e+'nine'+'nine'
        English
        >>> print(e+'nine'+'nine')
        infinity
        >>> print(sum(('one','two','three',), e))
        six
        >>> e+3
        Traceback (most recent call last):
            ...
        TypeError: unsupported operand type(s) for +: 'int' and 'str'
        >>> e+g
        Traceback (most recent call last):
            ...
        p.BabelError: incommensurate types
        >>> e+'x'
        Traceback (most recent call last):
            ...
        p.BabelError: incommensurate types
        >>> g.__class__(0)
        Traceback (most recent call last):
            ...
        TypeError: Valid constructor types are str, NoneType, and Deutsch
    '''
    
    import numbers
    from math import pi, copysign
    TAU = 2*pi # http://tauday.com/
    
    class BabelError(Exception):
        pass
    
    class base:
    
        '''
            support operations except for language module.
            Instantiating base by itself should be useless.
            Support language by providing a translation
            dictionary, as shown in the example derived classes.
        '''
    
        def __init__(self, value = None):
            if not hasattr(self.__class__, 'translation'):
                raise NotImplementedError('cannot instantiate base class')
            if not isinstance(value, (str, type(self), type(None))):
                raise TypeError('Valid constructor types are str, NoneType, and {}'.format(repr(self)))
            self.value = self.translate(value)
    
        def translate(self, value):
            '''
                convert the value to a number, or a number to a string
            '''
            if value is None:
                return 0
            if isinstance(value, self.__class__):
                return value.value
            translation = self.translation
            if value in translation:
                return translation[value]
            if isinstance(value, numbers.Number):
                return copysign(TAU, value)
            raise BabelError('incommensurate types')
    
        def __str__(self):
            v = self.value
            translation = self.__class__.translation
            if v in translation:
                return self.translate(v)
            return 'minus infinity' if v < 0 else 'infinity'
    
        @classmethod
        def new(cls, value):
            if isinstance(value, str):
                try:
                    return cls(value)
                except:
                    pass
                raise BabelError('incommensurate')
            result = cls()
            result.value = value
            return result
    
        def __add__(a, b):
            return a.new(a.translate(a.value + a.translate(b)))
    
        def __radd__(a, b):
            return a + b
    
        def __sub__(a, b):
            return a.new(a.translate(a.value - a.translate(b)))
    
        def __rsub__(a, b):
            return a.new(a.translate(a.translate(b) - a.value))
    
    def invert(d):
        '''
            >>> invert(dict(a = 97, b = 98))
            {97: 'a', 98: 'b'}
        '''
        return {value: key for (key, value,) in d.items()}
    
    def class_factory(d, name = None):
        d.update(invert(d))
        class c(base):
            translation = d
            if name:
                def __repr__(self):
                    return str(name)
        return c
    
    English = class_factory({key: value for (value, key) in enumerate('zero one two three four five six seven eight nine'.split())}, 'English')
    
    German = class_factory(dict(
        null = 0, eins = 1, zwei = 2, drei = 3, vier = 4,
        ), 'Deutsch')
    *difficult. help_desk is new to python. This code has a function that returns a class, decorators, left and right operator overloading, inheritance, sum with the initial value argument, error traps, ternary if operator, the dict constructor to implicitly generate strings via key word arguments, and dictionary comprehensions. And I managed to put in a plug for pi is wrong.
    [code]Code tags[/code] are essential for python code and Makefiles!
  8. #5
  9. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,837
    Rep Power
    480

    Response


    "why then didn't you just use my code which I understood to explain it to me or use another easy example that is very short. maybe a class with 2 methods and how that class was used in another file? like making that code into a class and writing another file.py where you show how to import that class and use it?"

    I know little about you, help_desk. What about your code should be made into a class? I can't ask this, you won't have an answer. When you import, the comes from a file. If you want examples, import sys, print(sys.modules), and investigate with a text editor some of the .py files in the paths you'll see. I use emacs. (As a side note, some of the homework questions clipped into these forums are written by professors using a word processor that replaces standard ASCII quotes with pretty looking unicode quotes. Python chokes on these. I find the professorial ignorance unbelievable.)

    I considered writing a short class to implement arithmetic modulus some number, a ring. "...with the operations of the ring of integers: addition, subtraction, and multiplication." Maybe your mathematical background is such that you'd have no interest and no comprehension. I figured that you'd understand addition and subtraction using words.

    Next, on account of that I post here to maintain or improve any programming skill I have, to learn, to read other peoples' codes, I choose fun tasks. For me. Next I'd want to incorporate my write_numbers function. Except that I'd then need to recognize written numbers which won't work for large numbers using the dictionary approach.
    Code:
    $ python3
    Python 3.3.1 (default, Apr 17 2013, 22:30:32) 
    [GCC 4.7.3] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import write_number
    >>> import pprint
    >>> import textwrap
    >>> pprint.pprint(textwrap.wrap(write_number.write_number(-9827407240287204874208723422)))
    ['negative nine octillion eight hundred twenty-seven septillion four',
     'hundred seven sextillion two hundred forty quintillion two hundred',
     'eighty-seven quadrillion two hundred four trillion eight hundred',
     'seventy-four billion two hundred eight million seven hundred twenty-',
     'three thousand four hundred twenty-two']
    >>>
    Also, to obtain preferred behavior the program became more involved than I expected. I followed my original plan, writing many of the tests first and then using a base class from which to subclass language support. I didn't realize from the outset that I could support languages entirely with a dictionary. A large number range would require a reworked translation system. The class factory was an afterthought. Constructing new classes is too difficult without it.
    Last edited by b49P23TIvg; July 13th, 2013 at 07:39 PM.
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo