Introduction

Hey everybody welcome to a tutorials on classes in PYTHON.
The purpose I made this tutorial for is that when I was learning classes in python I dint found any good tutorials on Classes. Maybe I was wrong. But here's my tutorial.

Layout

In this tutorial i'll be covering everything I know about classes.
Topics are as follows :-


1.What is an object?
2.What is a class? How do we declare it in python.
3.Declaring functions in Classes.
4.What is “self”?
5.Parent class and Child class.
6.How to inherit multiple classes.
7.Overwriting Variables

So let's get started.

What is an Object?

An Object is a key to understand the object oriented programming .If you are familiar with python you must have seen many functions like ctype.sqrt()... Etc etc.... Here you can suppose ctype as an object and sqrt as a method or function or whatever you call it.
Eg:- In the following statement aneesh.hot() aneesh is an object and hot is its atribute..Yeah ! I'll make it easy in a minute in the topic of classes ..

What are classes?

'A class defines' the abstract characteristics of a thing (object), including its characteristics (its attributes, fields or properties) and the thing's behaviors (the things it can do, or methods, operations or features). One might say that a class is a blueprint or factory that describes the nature of something. For example, the class Dog would consist of traits shared by all dogs, such as breed and fur color (characteristics), and the ability to bark and sit (behaviors). Classes provide modularity and structure in an object-oriented computer program.

Source : http://en.wikipedia.org/wiki/Object-oriented_programming#Class

So, above we came to know about the exact definition of classes.

Now ..

How do we declare a class in python?

Mind you guys its a bit confusing topic so I'll try to be as precise and simple as I could be.

In python we declare a class by

class classname :

where classname is the name of the class ...

Eg:-

class tutorials :
	name = “Classes in Python”
	difficulty= “easy”

Here , there are two variables declared in the class named tutorials one is name and another one is difficulty.

>> print tutorials.name
Classes in Python
>> print tutorials.difficulty
easy


Vola! It worked....

Not so cool ..huh!

Now, let us assign some objects to to the class

>> object1 = tutorials
>> print object1.name
Classes in python

“as expected”

Now lets do that with 2 objects.

>> object1 = tutorials()
>> object2 = tutorials()

# lets change the “name” variable , in tutorials
# this can be done with tutorials.name = “Hey there!”
# also with object1.name = “Hey there”

So let's do that :-

>> object1.name = “Hey there!”
>> print object1.name

Hey there
“As expected”

>> print object2.name
Classes in Python

The object2.name not changed.

The reason for this is that an object has its own class. The changes which object1 will make will stay to his class only. And the change that object2 will make will stay to his class.
This will seem quite confusing at this time but you'll understand it in the next topic..

So … I hope you understood this simple topic on “Classes with variables” in the next topic we'll be getting to some real stuff …. So hang in there...

Defining Methods/functions in classes

We'll start with our old boring class with nothing special in there.

class tutorials :
	name = “Classes in Python”
	difficulty= “easy”

ok now lets add some functions in there

class tutorials :
	name = “Classes in Python”
	difficulty= “easy”

	def printname(self,name) :
		print self.name

>> you = tutorials()
>> me = tutorials()
>> you.printname(“aneesh”)

class tutorials :

	name = "Classes in Python"

	difficulty= "easy"



	def yourname(self,yname):

		self.yname = yname



	def hello(self):

		print "Hello ",self.yname," !!!!"





#### Function call ####



obj1 = tutorials()		  # objt1 is an object of Class tutorials

obj2 = tutorials()		   # same here
obj1.yourname("Aneesh")	  # give “Aneesh” as input to the function yourname(self,yname) 
obj2.yourname("Yourname")# same here

obj1.hello()
			   # See below 
obj2.hello()
			   # see below

Realy simple code.

Explanation:-

What python does is that It goes al over the class and replaces “self” to the name of the object … In first case it is “obj1”.

So the source code becomes

class tutorials :

	name = "Classes in Python"

	difficulty= "easy"



	def yourname(self,yname):

		obj1.yname = yname



	def hello(self):

		print "Hello ",obj1.yname," !!!!"





#### Function call ####



obj1 = tutorials()		# objt1 is an object of Class tutorials

obj1.yourname("Aneesh")	

obj1.hello()

So self is a temporary place holder for object.
Now does that make sense?

Yeah! I'll make it more clear in the next topic.

Parent and Child class [Subclasses and superclasses]

This feature is usefull when you want to add some variables in the one class without actually writing the code all over again .. Or copy pasting[which can make your code so unreadable] ….

lets make some new classes :-

class parentclass :

	name = "Im D parent”


class childclass(parentclass) :

	var = "Hey i am d child"

Above I declared 2 classes “parentclass and childclass”

But wait. I actually provided some input to child class . In python that means the childclass inherit attributes from parentclass.

Lets test that

>> obj1 = childclass()

>>print obj1.name

I m D parent

voila …..
So simple ….

Now what about if a child has to inherit attributes from multiple parents.
Heres it:-

class parentclass :

	name = "Im D parent"



class parent2 :

	name2 = " i am parent 2 , HEHEHEHEHHE"

		

class childclass(parentclass,parent2) :

	var = "Hey i am d child"

In python to inherit attributes from multiple classes we use a “comma”[as a separator] and input the classes . In this case (parentclass,parent2)
Now lets test it

>>
obj1 = childclass()

>> print obj1.name2

I am parent 2 , HEHEHEHEHHE

You can overwrite these variables also as done before

>> obj1.name2 = “ Hey I am the child and I have overwritten you”
>> print obj.name2
Hey I am the child and I have overwritten you


This was all I know about Classes.. Fell free to add comments...
Thanks for reading..


jcao219 commented: Very helpful to beginners, who often struggle to understand OO +1

In math.sqrt the math is module and sqrt is function. Nothing to do with objects.

In math.sqrt the math is module and sqrt is function. Nothing to do with objects.

Well, not exactly nothing to do with objects, if you realize that functions are in fact objects.
But you are right, math is the module.

Overall, very good tutorial on the basics of classes and objects.

To be honest, I hoped this post would tell us how to turn classes into strings,
but that would make our minds explode.
Someday I might post a tutorial about that.

Thanks guyz ... Sorry, but i am a beginner in python...
Sorry for all the flaws in this tutorial..

It's a very good tutorial, though.
It took me a long time to finally understand the concept of objects in Python, and writing a tutorial on it is also very challenging.
Your explanation of "self" is very good; beginners can easily understand that.
Good job!

self though is convention, you can give any name you like. It is very sensible to generally keep to that convention. Another convention I would like mentioned is using Capitalized names class names and only for them, not for example for modules math not Math. There is confusion in this issue, which is being corrected (Tkinter etc)

Just a quick point.
To turn an object into string, you can define the special method __repr__ in your object :

class myobject:
    def __init__(self, name):
        self.name=name

    def __repr__(self):
        return "my name is %s" % (self.name)

o=myobject("toto")

print o

> toto

sorry

print o

> my name is toto

sorry

print o

> my name is toto

That's not what I was talking about.
I said turn classes into strings.
Want to see?
I can post it as a code snippet.

Hey guys if you dont mind can you add to my reputation points if you liked the tutorial.... I really need them.......

Hey guys if you dont mind can you add to my reputation points if you liked the tutorial.... I really need them.......

If you create posts that are very useful and helpful, and also very well written, they will be voted up.
But also, don't post something just for the sake of getting reputation points,
that is not effective.
Instead, put lots of thoughtful effort into each and every post and reply that you make, and gradually each vote will add up.
Be sure to reread everything you write after submitting them, too, to see if they add positively to the discussion while respecting the work of others. That is what the edit button is for.
That is how you get a good reputation on Daniweb.

commented: The zen of posting ! +3

are there main() function in python??? if not, how do u create objects for the defined classas??

commented: Out of topic of the thread, keep it organized, start own thread! -3
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.