#1
  1. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2004
    Location
    There where the rabbits jump
    Posts
    556
    Rep Power
    11

    Classes are for???


    Okay hi
    I guess i am back

    At the moment I am reading about classes in my book.
    But I don't understand how to use them or why to code them?
    Could someone give an example and then explain what it is for.

    And here the "self" thing in so called methods(functions in classes).
    What is "self" for I don't understand what the purpose is?

    Thanks for any help
  2. #2
  3. Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Dec 2004
    Location
    Meriden, Connecticut
    Posts
    1,797
    Rep Power
    154
    Classes are actually pretty simple. Here's a quick example of what I used for one of my classes.
    Code:
    class StartSafelist:
        if not os.path.isfile('safelist.txt'):
            print 'Could not find safelist.txt!'
            safefound = False
        else:
            safefound = True
            fileSafe = open ( 'safelist.txt' )
            fileList = fileSafe.readlines()
            for item in fileList:
                tempSafe.append(item)
            for item in tempSafe:
                item = item.replace('\n', '')
                safelist.append(item)
            fileSafe.close()
    class FoundSafe:
        safesent = ['boolean']
        if StartSafelist.safefound == True:
            pass
        else:
            while True:
                if os.path.isfile('safelist.txt'):
                    StartSafelist.safefound = True
                    print 'safelist.txt has been found!'
                    StartSafelist
                    break
                elif not os.path.isfile('safelist.txt'):
                    pass
                else:
                    pass
    Now, this code is checking to see if the file exists or not. I have this code located near the top of my program so it will run immediately. Say you need to read/write something to a file and you need to know if it exists or not, you would do:
    if StartSafelist.safefound == True. This way you couldn't have to do all of the code again. It's a bit like a definition only it is much more useful and capable of mroe things. When you're using things like .self and you're using definitions inside of your class, it gets more complicated. Try reading the Classes section in the python.org tutorial, it's very helpful.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2004
    Location
    There where the rabbits jump
    Posts
    556
    Rep Power
    11
    Ya I saw the code in the other thread but if it is not there (like netytan) why dont you just do: file = open('file.txt')
    and okay i'll look at the python.org tutorial
    thanks
    Edit: I just rememberd
    Why would i use classes it is also possible the other way?
  6. #4
  7. Commie Mutant Traitor
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Jun 2004
    Location
    Alpharetta, GA
    Posts
    1,806
    Rep Power
    1570
    Classes are primarily a way to organize and encapsulate (that is, separate some parts of the code from other parts so that they don't end up depending on each other unnecessarily) different kinds of data structures.

    Actually, the important part is not the classes themselves, but the objects which you create from them; this is why it is called 'object-oriented programming'. The idea is basically to be able to create a new data type along with a set of methods (functions that are part of the class) that operate on the variables of that type. So, if you had a class Vehicle, you might give is an instance variable (variables that are part of the larger data structure of the objects) speed, max_passengers, and so on, and such methods as accelerate(), decelerate(), and so forth (example code, not tested):

    Code:
    class Vehicle:
        def __init__(self, p)
            self.max_passengers = p
            self.speed = 0
            
        def accelerate(self, delta)
            self.speed += s
            return self.speed
    
        def decelerate(self, delta)
            if delta > self.speed:
                self.speed = 0
            else:
                self.speed -= delta
            return self.speed
    Then you could assign an object of that class to a variable
    and use it as if it were part of the language:
    Code:
    my_vehicle = Vehicle(4)
    
    my_vehicle.accelerate(55)
    
    
    print(my_vehicle.decelerate(5))
    ... which should print out '50'.

    Another part of Object-Oriented programming is to treat the object variables as if the were active agents in their own right, rather than passive pigeonholes for putting data into. A certain amount of anthropomorphizing helps: rather than thinking of a function take a value from a variable, doing something with it, and returning another value, you think of the method invocation (that is, the function call) as telling the variable to change itself based on the value of the argument.

    A third part of object-oriented programming is being able to create new classes from existing ones by extending or specializing them; this is called inheritance. So if you had the class Vehicle from before, you could then create a subclass Car that would have it's own versions of the accelerate() and decelerate() methods, and additional instance variables such as year and model. Furthermore, because it is a subclass of Vehicle, you can use a Car object anywhere you would expect to have an object of the general Vehicle class.

    This approach, like all others, has it's good points and bad points. It is most useful when dealing with complex but discrete object types such as windows or cursors, or for complex simulations; it does rather poorly with heavily interconnected data, like in a relational database, or with very simple data types such as numbers. Also, it can be tricky to understand it, and trying to use it just for it's own sake if you don't work well with it can be disasterous. YMMV as to when, how and if to use the object-oriented aproach rather than some other approach.
    Last edited by Schol-R-LEA; February 5th, 2005 at 04:49 PM.
    Rev First Speaker Schol-R-LEA;2 JAM LCF ELF KoR KCO BiWM TGIF
    #define KINSEY (rand() % 7) λ Scheme is the Red Pill
    Scheme in ShortUnderstanding the C/C++ Preprocessor
    Taming PythonA Highly Opinionated Review of Programming Languages for the Novice, v1.1

    FOR SALE: One ShapeSystem 2300 CMD, extensively modified for human use. Includes s/w for anthro, transgender, sex-appeal enhance, & Gillian Anderson and Jason D. Poit clone forms. Some wear. $4500 obo. tverres@et.ins.gov
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Posts
    624
    Rep Power
    34
    Originally Posted by †Yegg†
    Classes are actually pretty simple. Here's a quick example of what I used for one of my classes.
    Code:
    class StartSafelist:
        if not os.path.isfile('safelist.txt'):
            print 'Could not find safelist.txt!'
            safefound = False
        else:
            safefound = True
            fileSafe = open ( 'safelist.txt' )
            fileList = fileSafe.readlines()
            for item in fileList:
                tempSafe.append(item)
            for item in tempSafe:
                item = item.replace('\n', '')
                safelist.append(item)
            fileSafe.close()
    class FoundSafe:
        safesent = ['boolean']
        if StartSafelist.safefound == True:
            pass
        else:
            while True:
                if os.path.isfile('safelist.txt'):
                    StartSafelist.safefound = True
                    print 'safelist.txt has been found!'
                    StartSafelist
                    break
                elif not os.path.isfile('safelist.txt'):
                    pass
                else:
                    pass
    This is very contorted code - call os.path.isfile to see if the file exists, then save the output of that somewhere else, open the file, read all the lines and and return them as a list. Iterate through the list adding all the items to a list. Iterate through that list stripping the newlines and adding them to another list.

    Create a list containing a string that says 'boolean' (???) then test something and do nothing with the answer, otherwise go into an endless loop in which you call os.path.isfile again which returns True or False, but you have a three-way if statement(!), which ignores the contents of StartSafelist.safefound and then resets it, then addresses the class StartSafelist then breaks out of the infinite loop. Otherwise it does nothing.


    If all you want is to test if the file exists, call os.path.isfile() (once).
    If you want the contents, use file.readlines().
    If you want the contents with no newline characters, use strip() on the line (which will catch carriage return and line feed (\r and \n)).
  10. #6
  11. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2004
    Location
    Bimingham,AL
    Posts
    68
    Rep Power
    11

    This i guess is not an python question


    Do some googling on object oriented philosphy and its uses . you will know what classes are for .
  12. #7
  13. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    Originally Posted by †Yegg†
    ...
    Now, this code is checking to see if the file exists or not. I have this code located near the top of my program so it will run immediately. Say you need to read/write something to a file and you need to know if it exists or not, you would do:
    if StartSafelist.safefound == True. This way you couldn't have to do all of the code again. It's a bit like a definition only it is much more useful and capable of mroe things. When you're using things like .self and you're using definitions inside of your class, it gets more complicated. Try reading the Classes section in the python.org tutorial, it's very helpful.
    Monkey, you would probably bet better if you ignore the code in this post, since as sbf so elegantly put it "This is very contorted code". This isn't really how you would want to use a class anyway and it could/should be be done with a function instead .

    Keep in mind that a class is not the same as a function (although functions in Python are first member classes), both have different uses and are better at different things.

    In either case It's generally not a good idea idea to try and use a function like it were a class; even if Python doesn't stop you doing it.

    Later guys,

    Mark.
    programming language development: www.netytan.com Hula


IMN logo majestic logo threadwatch logo seochat tools logo