I am trying to learn object oriented programming and am still shaky on the ins and outs of classes. I understand their purpose, but can't seem to grasp many simple operations when using them.

The dive into python section on classes is not very helpful either, so if you know any resources, please let me know.

Here is what I seek to do:

Make a class that reads in data from a file.
Strips white space and splits the data.
Prints the output to the screen.

I seek to do that using classes.

Here is an attempt:

class FormatData:
	"""
	CLass to take data file and format it to my liking
	"""

	def __init__(self, file=none):


		infile = open(file)
		for line in infile: 
			line = line.strip()
                        sline = line.split()		      
                        print sline

The code runs, but nothing prints to the screen. I don't understand how to run this code properly. Unfortunately, the project I am working on has this identical operation stored in a class, and then goes on to create a dictionary so I need to understand this before I move on. Why is it not printing to screen? Do I have to do something special since I am working in classes?

Editor's note: Please do not mix tabs and spaces in your Python code! Proper indentations are just too important with Python. Avoid tabs.

Recommended Answers

All 4 Replies

You need to instantiate the class by creating an instance of it. So if your class is called FormatData as in your example above, you would create an object like so:

# Assuming the class FormatData has 
#  already been defined or imported from 
#  another module...
def main():
    print 'Hello, welcome to my class test program'
    my_class_object = FormatData( '/usr/foo/bar.txt' )
    # When creating the object, __init__ is called
    # Let's pretend the class contains a function:
    #  def foobar_you( self ):
    # To call it, you would do something like:
    my_class_object.foobar_you()
    print 'Thanks for running this program, bye!'
    return

Now, that aside I must say that IMHO it seems like your objective would be better suited to be achieved by a function rather than a class. Then again, I understand you're simply trying to learn how to create and use classes and not particularly planning on using this class in the future.... Just my $0.02

Thanks guys, I will go through, and try to understand/reproduce your suggestions tomorrow morning. jlm669, you are right that this is better suited to a function, but it's just a small snippet from a bigger code I'm working in, so I have no choice but to consider it from an object oriented perspective. It's neat actually what the code does. It takes in data about the raw human genome from the UCSC Genome Browser data base and builds a dictionary by chromosome and then outputs the data into more useable forms. The dictionary part is neat, but is still confusing me a bit.

Also, to the mod who edited my post, sorry about that. I'll be more aware of my need to proofread.

Here is a cute example of the use of a Python class. It shows you how the class is used to group functions/methods together, and how one class can inherit another class or multiple other classes ...

# basic experiments with Python class

class Cat(object):
    # this is public
    cost = 100
    # this is private to the class
    __price = cost + cost * 0.25  
    # constructor
    def __init__(self, num=1):
        self.num = num
        self.sound = "meow " * self.num
        print self.sound
 
    def own(self):
        print "I own", self.num, "cats"

    def paid(self):
        self.total = self.__price * self.num
        print "I paid", self.total, "for my cats"
        
    def kitten(self):
        self.kit = 5
        print "One cat just had", self.kit, "kittens"
        return self.kit


class Dog(object):
    # this is public
    cost = 400
    # this is private to the class
    __price = cost + cost * 0.25  
    # constructor
    def __init__(self, num=1):
        self.num = num
        self.sound = "woof " * self.num
        print self.sound
 
    def own(self):
        print "I own", self.num, "dogs"

    def paid(self):
        self.total = self.__price * self.num
        print "I paid", self.total, "for my dogs"
        

class Pets(Cat, Dog):
    """class Pets inherits class Cat and class Dog"""
    # constructor
    def __init__(self):
        self.num = cat.num + dog.num
        self.sound = cat.sound + dog.sound 
        print self.sound
 
    def own(self):
        print "I own", self.num, "pets"

    def paid(self):
        print "I paid", dog.total + cat.total, "for my pets"
        
    def update(self):
        # notice how Pets inherited kitten() from class Cat
        self.kit = self.kitten()
        print "So now I have", self.num + self.kit, "pets"
        

# create an instance of class Cat
cat = Cat(3)
cat.own()
cat.paid()

print '-'*30

# create an instance of class Dog
dog = Dog(2)
dog.own()
dog.paid()

print '-'*30

# create an instance of class Pets
pets = Pets()
pets.own()
pets.paid()

print '-'*30

pets.update()

"""
my output -->
meow meow meow 
I own 3 cats
I paid 375.0 for my cats
------------------------------
woof woof 
I own 2 dogs
I paid 1000.0 for my dogs
------------------------------
meow meow meow woof woof 
I own 5 pets
I paid 1375.0 for my pets
------------------------------
One cat just had 5 kittens
So now I have 10 pets
"""
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.