python logo

python class


Python hosting: Host, run, and code Python in the cloud!

Introduction to Python Classes
The landscape of technology has always been evolving, and so has the way we program. In our journey of understanding Python, we encounter the concept of classes. But before we delve into that, let’s trace back a bit. Where did classes originate from?

1. Statements:
In the initial stages of computing, programmers only wrote commands or statements to communicate with machines.

2. Functions:
To make code more modular and readable, functions were introduced. These are reusable groups of statements that structure the code better.

3. Classes:
Enter the world of classes, the heart of object-oriented programming (OOP). With classes, we create objects. These objects have both functions (methods) and variables. A good example would be strings in Python. For instance, a string variable named ‘book’ has methods like book.replace() and book.lower(). This programming paradigm, where we model real-world objects, is commonly referred to as object-oriented programming.

Let’s further explore this concept.

Recommended Python Course:
Python Programming Bootcamp: Go from zero to hero

Understanding Python Classes
In Python, classes allow us to craft virtual objects. These objects can house both variables (often called attributes) and functions (referred to as methods). For instance, consider the following class:

1
2
3
4
5
6
7
8
class User:
name = ""

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

def sayHello(self):
print("Hello, my name is " + self.name)

Here, we have a class User with an attribute name and a method sayHello. We can create instances of this class like so:

1
2
3
james = User("James")
david = User("David")
eric = User("Eric")

James, David, and Eric are all instances (or objects) derived from the User class.

Python Class: create objects

In the User class, we’ve also defined a method sayHello(). That’s why we’re able to call it on each of the objects. The special method __init__() is termed as the constructor. This is automatically invoked whenever a new object is created. Attributes associated with a class, like name in this case, are commonly known as class attributes.

Classes also grant us the capability to define methods that modify the internal state (or attributes) of an object. To illustrate this, let’s dive into another example.

Class Attributes and Their Manipulation
Imagine a scenario where we want to model a coffee machine. This machine will have attributes to store the amount of beans and water. We’d also want methods to add or remove beans and water. Here’s how we can model this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class CoffeeMachine:
name = ""
beans = 0
water = 0

def __init__(self, name, beans, water):
self.name = name
self.beans = beans
self.water = water

def addBean(self):
self.beans += 1

def removeBean(self):
self.beans -= 1

def addWater(self):
self.water += 1

def removeWater(self):
self.water -= 1

def printState(self):
print("Name = " + self.name)
print("Beans = " + str(self.beans))
print("Water = " + str(self.water))

The above class, CoffeeMachine, has attributes name, beans, and water. The methods allow us to manipulate these attributes. For instance:

1
2
3
4
5
pythonBean = CoffeeMachine("Python Bean", 83, 20)
pythonBean.printState()
print("")
pythonBean.addBean()
pythonBean.printState()

On running this, we’d get an output like:

1
2
3
4
5
6
7
Name  = Python Bean
Beans = 83
Water = 20

Name = Python Bean
Beans = 84
Water = 20

This showcases how the internal state of our pythonBean object changes as we invoke methods on it.

Download Exercises to Enhance Your Python Skills

Previous | Next






Leave a Reply:




Wenlf Thu, 14 May 2015

if when we define a class , self is always there?

Frank Thu, 14 May 2015

self is a reference to the variables in the functions. That is to say, self can be used anywhere inside the class but not outside it. What you are instructing the computer is "I want to access variables from this class.". This is always from within a method inside the class. You should see 'self' as the assignment of the variables in logic, not as ownership for all bojects.

I think an example will be more clear, it's in pseudo code:


class User:
y = 0

def doSomething(x):
print x

def somethingElse(y):
self.y = y

If you create an object (user) randy and call randy.doSomething(3), the variable is not stored anywhere. If you call randy.somethingElse(3), randy.y will contain y because of the assignment with self.y

Every object created from a class has it's own variable assignments. You could have a User and create 3 users from the class. Each of the user objects can have its own name, email, age.

Gs Thu, 04 Jun 2015

Would it be possible to add the solutions to the exercises as a spoiler format/pop up so that one can check their code?

Frank Thu, 04 Jun 2015

Hi! These are the answers to the questions, I tried them on Python 2.7.6. If anything doesn't run or want more explanation, let me know. Here you go:

*** spoiler, answer to exercises ***

Part 1: Classes in Python

1 and 2:

class User:
name = ""

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

def sayHello(self):
print "Hello, my name is " + self.name

# create virtual objects
james = User("James")
david = User("David")
eric = User("Eric")

# call methods owned by virtual objects
james.sayHello()
david.sayHello()
eric.sayHello()

3:

class User:
name = ""

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

def sayHello(self):
print "Hello, my name is " + self.name

def sayBye(self):
print "Goodbye"



# create virtual objects
james = User("James")
david = User("David")
eric = User("Eric")

# call methods owned by virtual objects
james.sayHello()
david.sayHello()
david.sayBye()

5.

class User:
name = ""

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

def sayHello(self):
print "Hello, my name is " + self.name

# create virtual objects
james = User("James")
david = User("David")
eric = User("Eric")
brian =User("Brian")
tamara = User("Tamara")
abbey = User("Abbey")

# call methods owned by virtual objects
james.sayHello()
david.sayHello()
brian.sayHello()
tamara.sayHello()
abbey.sayHello()

Part 2: Changing internal variables

1, 2:

class CoffeeMachine:
name = ""
beans = 0
water = 0

def __init__(self, name, beans, water):
self.name = name
self.beans = beans
self.water = water

def addBean(self):
self.beans = self.beans + 1

def removeBean(self):
self.beans = self.beans - 1

def addWater(self):
self.water = self.water + 1

def removeWater(self):
self.water = self.water - 1

def printState(self):
print "Name = " + self.name
print "Beans = " + str(self.beans)
print "Water = " + str(self.water)

pythonBean = CoffeeMachine("Coffee Machine", 83, 20)
pythonBean.printState()
print ""
pythonBean.addBean()
pythonBean.addBean()
pythonBean.addBean()
pythonBean.printState()

3.

class CoffeeMachine:
name = ""
beans = 0
water = 0

def __init__(self, name, beans, water):
self.name = name
self.beans = beans
self.water = water

def addBean(self):
self.beans = self.beans + 1

def removeBean(self):
self.beans = self.beans - 1

def addWater(self):
self.water = self.water + 1

def removeWater(self):
self.water = self.water - 1

def printState(self):
print "Name = " + self.name
print "Beans = " + str(self.beans)
print "Water = " + str(self.water)

pythonBean = CoffeeMachine("Python Bean", 83, 20)
pythonBean.printState()
print ""
pythonBean.addBean()
pythonBean.printState()


beanMachine = CoffeeMachine("Python Machine 2", 83, 20)
beanMachine.printState()
print ""

goodmachine = CoffeeMachine("Python Machine 3", 83, 20)
goodmachine.printState()
print ""

Hyper.Hydra Sat, 20 Jun 2015

hello i tried this but it didn't run can you help me?

sorry for my bad english.
thanks

Frank Sat, 20 Jun 2015

Hi, are you getting any error? Which exercise did you try?
I tested them with Python 2.7.6. If you are using Python 3 put brackets around the print command, such that print("command").
Do you happen to speak Dutch (Nederlands) by any chance? (translated below)

Hyper.Hydra Sat, 20 Jun 2015

Yes, I speak dutch.

Frank Sat, 20 Jun 2015

Which error do you get?

Hyper.Hydra Sat, 20 Jun 2015

I get this error:
Traceback (most recent call last) :

Frank Sat, 20 Jun 2015

What is written below Traceback? Which program?

Hyper.Hydra Sat, 20 Jun 2015

I created a screenshot:
https://pythonspot.com/wp-content/uploads/2015/06/screenshot.jpg

Frank Sat, 20 Jun 2015

You are in the Python shell, copy the code to a file named test.py and execute using: execfile('test.py').

$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:38)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> execfile('test.py')

Alternative:

C:Python27python.exe C:UsersUsernameDesktoptest.py
Hyper.Hydra Sat, 20 Jun 2015

What should happen? A command line screen appears but is gone within a second.

Frank Sat, 20 Jun 2015

Press windows key + R (start, run), type command or cmd. A command line screen will appear, then:

C:Python27python.exe C:UsersUsernameDesktoptest.py
Hyper.Hydra Sat, 20 Jun 2015
C:UsersEigenaarDesktoptest.exe wordt niet herkend als een interne
of externe opdracht, programma of batchbestand.
krijg ik dan te zien.
Frank Sat, 20 Jun 2015

The file does test.exe does not exist. From the command line run python.exe with the parameter to the path test.py.

C:Python27python.exe C:UsersUsernameDesktoptest.py

Of course the path must be correct. You could use a GUI like PyCharm if you prefer.

Abdala Mon, 06 Jul 2015

Hey Frank I'm new in python i just want to understand what does " " means when u write name = " " what does it store? thank you

Frank Mon, 06 Jul 2015

Hi, when a new object is created using a class, this object will have the string variable name. This string value will have an empty string.
In this case, the virtual objects james, david and eric have a variable name. We set this name in the constructor __init__(self, name).

N Goutam Thu, 23 Jul 2015

Hey frank, could you please elaborate on what a constructor does and why is it used?

Frank Thu, 23 Jul 2015

Hi, the constructor function is only called when creating a new object. This function can initialize the variables of that particular object. In the case of class User, the constructor is used to set the name variable. We call the constructor with:

james = User("James")
david = User("David")
eric = User("Eric")

And the constructor sets the variable name:

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

Constructors are typically only used to initialize variables of objects.

Yogesh Waghmare Mon, 27 Jul 2015

Change the order and amount of sayHello() calls

please let me no about this Exercises, I am not getting

Frank Mon, 27 Jul 2015

Hi, this simply means to change the number of calls to sayHello() and the order. For example:

david.sayHello()
james.sayHello()
david.sayHello()
david.sayHello()
Vief Mon, 27 Jul 2015

Hi! Could you maybe answer this same question in Dutch?

Frank Mon, 27 Jul 2015

Het 'self' keyword bestaat alleen binnen de klasse. Het gebruik van 'self' beperkt zich tot binnen de methoden. Het doel van self is het toekennen van waarden en aanroepen van methoden binnen de eigen klasse.

Vitaliy Fri, 31 Jul 2015

I'm migrating from Java, so I'm just wondering - why there is a basic difference between function declaration and a class method with using a 'function' keyword. In class method you are not allowed to use this keyword while for simple function declaration - it work in both cases - with and without using keyword ?

Frank Fri, 31 Jul 2015

Hi Vitaliy, do you mean the self parameter?

The self parameter needs to be specified for classes by design, which is not necessary in Java.

Explicitly defining the self parameter is needed for these reasons:
<ul>
<li>Local variables are all variables in the function body (by definition). Self is the only method to access class variables. From a Java perspective, it is similar to some coding standards that require m_ or m to be added before the variable name, where 'm' implies member of the class. The difference being that in Python its not optional. </li>
<li>If you want to call the method from a particular class, no special syntax is necessary. </li>
<li>Reading self.x or self.task() makes it absolutely clear that an instance variable or method is used.</li>
</ul>

James Thangjam Thu, 20 Aug 2015

this giving error


class User:
name = ""
def __init__(self, name):
self.name = name
def sayHello(self):
print "Hello, my name is " + self.name
# create virtual objects
james = User("James")
david = User("David")
eric = User("Eric")
# call methods owned by virtual objects
james.sayHello()
david.sayHello()

SyntaxError: invalid syntax
second ex :


class CoffeeMachine:
name = ""
beans = 0
water = 0
def __init__(self, name, beans, water):
self.name = name
self.beans = beans
self.water = water
def addBean(self):
self.beans = self.beans + 1
def removeBean(self):
self.beans = self.beans - 1
def addWater(self):
self.water = self.water + 1
def removeWater(self):
self.water = self.water - 1
def printState(self):
print "Name = " + self.name
print "Beans = " + str(self.beans)
print "Water = " + str(self.water)
pythonBean = CoffeeMachine("Python Bean", 83, 20)
pythonBean.printState()
print ""
pythonBean.addBean()
pythonBean.printState()

SyntaxError: invalid syntax

Frank Thu, 20 Aug 2015

Hi James,
Save all of the code to a file called program.py then start the interpreter with a Python file: python program.py

Ben Fri, 21 Aug 2015

Hi, the Class method's 1st parameter must be self ?

Frank Fri, 21 Aug 2015

Yes, this is a requirement in Pythons implemention of object orientation. Every method in a class needs to have self, but for methods outside the class that is not necessary.

Radu Sat, 22 Aug 2015

Hey Frank, what is the purpose of the class variables, i see you don't use them at all. Are those class attributes of that particular instance? Thanks mate

Frank Sat, 22 Aug 2015

Hi Radu,
When you create 'virtual objects', the new objects created have these variables. Yes, they are variables accesible for new instances.
For example: If we create a class Mail, every Mail object can have several variables like sender, to, title, message, date.

#!/usr/bin/env python

# Create class
class Mail:

def __init__(self,sender,to,title,message,date):
self.sender = sender
self.to = to
self.title = title
self.message = message
self.date = date

def showTitle(self):
print("Mail title = " + self.title)

# Create two virtual objects
workMail = Mail("[email protected]",
"[email protected]",
"Meeting",
"Hi, the meeting is rescheduled to ... ",
"22-08-2015")

friendMail = Mail("[email protected]",
"[email protected]",
"Party",
"Hi, do you wanna hang out ...?",
"20-08-2015")

# Use virtual objects
workMail.showTitle()
Radu Sat, 22 Aug 2015

Thanks for the example, so these are instance variables(self.sender, self.title etc.)that are unique per object(workmail and friendmail) in this case right? But i was referring to class variables from your main example above, those before the __init__ constructor (eg. name = '', beans = 0, water = 0). Why did you used them? Was that necessary? Sorry for this maybe, dumb questions. I'm in my early stages of programming and you know how it is.. Thanks again!

Frank Sat, 22 Aug 2015

Hi Radu,

Thanks for the example, so these are instance variables(self.sender, self.title etc.)that are unique per object(workmail and friendmail) in this case right?


Right


But i was referring to class variables from your main example above, those before the __init__ constructor (eg. name = ", beans = 0, water = 0). Why did you used them? Was that necessary?

These are similar to those defined inside the __init__, they are variables unique per instance. Every Coffeemachine instance has these variables. In some other languages (Java, C#, C++) they need to be on the top, but in Python it's fine if you define them in __init__ only. Thus, in Python you can choose which you prefer

Radu Sat, 22 Aug 2015

Okey, thanks. Then i will initialize/use them in __init__ only if you say so, i guess it is more readable from my point of view, which belongs to which and so on.

Saqib Ali Khan Tue, 25 Aug 2015

Hi Frank,
in above example, the Class variables ( Bean, name, water), are they global variables? how and where do we define/declare Global Variables?
Thanks

Frank Tue, 25 Aug 2015

Hi Saqib Ali khan,
They are class variables. Every new object will have these variables. These variables belong to objects and are not global variables. A global variable should be defined on top of the code, and use 'global' inside a function to access it

Ben Wed, 26 Aug 2015

self is not key word ,right ? I use it replace self and it's going well

class CoffeeMachine:
name = ""
beans = 0
water = 0

def __init__(it, name, beans, water):
it.name = name
it.beans = beans
it.water = water
Frank Wed, 26 Aug 2015

Hi, this works in both python 2.5 and 3. The first argument is often called self, which is nothing more than a convention. By not following the convention your code may be less readable to other Python programmers. The reason you need self (or the name you pick), is because Python uses it to refer to object attributes.

Than Thu, 10 Sep 2015
class User:
name =""

def __init__(self, name):
self.name = name
def sayHello(self):
print "Hello, my name is " + self.name
james = User("James")
SyntaxError: invalid syntax
Frank Thu, 10 Sep 2015

Hi Than,

If you use Python 3 use brackets around the print statement. Make sure you use four spaces, Python is very strict about that.
Try the code below:

class User:
name =""

def __init__(self, name):
self.name = name
def sayHello(self):
print("Hello, my name is " + self.name)

james = User("James")
james.sayHello()


Good luck!

Gloomshroud Fri, 16 Oct 2015

Wow...you offer all these awesome tutorials in English...and then you also provide translation to Dutch when needed. You are the MAN. I'm not a Dutch-speaker, but that is still so awesome. I just wanted to say thank you for all of your efforts. I'm really knocking this down (I come from a C#/Java background) thanks to your clear, concise, and thorough instruction!

Ravali Mon, 16 Nov 2015

What is the purpose of the special functions inside a class construct?

Frank Mon, 16 Nov 2015

The functions in a class can be called when an object is created. Take for example, the object james. The function james.sayHello() can be called, but is defined in a class.

Sadia Thu, 17 Dec 2015

Hi Frank,
i am begginer in python. kindly if you could let me know in this code what is meaning of this line [desc_str = "%s is a %s %s worth $%.2f." % (self.name, self.color, self.kind, self.value)].
what is % and .2f? what this line is doing?

class Vehicle:
name = ""
kind = "car"
color = ""
value = 100.00
def description(self):
desc_str = "%s is a %s %s worth $%.2f." % (self.name, self.color, self.kind, self.value)
return desc_str
car1=Vehicle();
car2=Vehicle();
print car1.description()
print car2.description()
Frank Sat, 19 Dec 2015

Hi Sadia, %.2f will format the variable as a number with two digits in the end. Take for illustration:

print "%.2f" % (2.15938)

Which will output 2.16. The 'f' in %.2f tells Python to use a floating point number (a number with digits after the comma)

Sadia Sun, 20 Dec 2015

Dear Frank,
Please if you could elaborate the lines of your program as i have done work in java so i am bit confused. i have written my questions with code lines. Please also let me know is it compulsory to make init as you said it is constructor. like in java one can make constructor if it needs but it is not compulsory.

class User:
name = "" // what is this in python? in java such variables are called instance variables and can
be accessed through object

def __init__(self, name): // what is self is it like "this" in java? is "name" inside () is local variable?
self.name = name //in java when local variable and in-
stance variable have same name then "this" is used with instance variable. is this the case over here too? is the "name" on left side is one that is declared above init and on right side is that which is inside init?

def sayHello(self):
print "Hello, my name is " + self.name //this name is which one as there is name inside init and
also above init?

# create virtual objects
james = User("James")
david = User("David")
eric = User("Eric")

# call methods owned by virtual objects
james.sayHello()
david.sayHello()
Sumit Mon, 21 Dec 2015

In OOPS programming languages like C++ and Java, We have Access levels like Public, Private and Protected type within classes. Do Python supports these access levels in classes. If yes, can you give me an example referring all these 3 within same class

Frank Sat, 26 Dec 2015

You can emulate private variables using the __ prefix. Variables like __foo are not visible outside the class, but you can access them if you workaround. There is no protected in Python. By default all variables are public

Frank Sat, 26 Dec 2015

Making a constructor is optional in Python. Name is a class variable. Pythons self is like this in Java. The name in sayHello (self.name) is similar to Javas (this.name).

Sadia Tue, 29 Dec 2015

Dear Frank, Thank you for explaining. Sorry for bothering again. if without using self the following program that i have tried is giving correct output then what is need to write self inside method. Secondly in this code shall we say that c is a local variable? it is clear to me that those variables which are inside class but outside method are called class variables but what about a and b. what term will be used for them?

class Coff:
def addBeans(self,a,b):
a=a;
b=b;
c=a+b
#print(c)
return c

m=Coff()
print(m.addBeans(3,4))
Frank Thu, 31 Dec 2015

Hi Sadia, no problem. The program is object oriented, you create the object 'm' of the type 'Coff'. self is just a variable name, it represents the instance object. In a functional program, there are no objects.

Good question. The variables a and b are parameters because we put them in the definition: addBeans(self,a,b). Variable c can be called local variable or a method variable, because it exists only in addBeans().

Hina Tue, 05 Jan 2016

Hi Frank.
please if you tell me what is Solver().demo()? i know demo method is gonna call by class Solver but to call method object of class is made and then through it method is called. why i am getting error if i replace this line with these lines: obj=Solver(); obj.demo(); I know through class name we can access methods and class attributes but why () with Solver ?

class Solver:
def demo(self):

a = int(input("a "))
b = int(input("b "))
c = int(input("c "))
d = b ** 2 - 4 * a * c
disc = math.sqrt(d)
root1 = (-b + disc) / (2 * a)
root2 = (-b - disc) / (2 * a)
print(root1, root2)

Solver().demo()
Frank Fri, 08 Jan 2016

Hi, you could do this:

class Solver:
def demo(self):

a = int(input("a "))
b = int(input("b "))
c = int(input("c "))
d = b ** 2 - 4 * a * c

if d < 0:
print("d is negative.")
else:
disc = sqrt(d)
root1 = (-b + disc) / (2 * a)
root2 = (-b - disc) / (2 * a)
print(root1, root2)

obj=Solver()
obj.demo()

I added a check to test if d is negative. Sqrt on negative numbers is impossible without the use of imaginary numbers. As you using a quadratic equation I think you want to use real numbers. If you enter a=2, b=4, c=-4 you will get the two roots.

Shiney Wed, 24 Feb 2016

Please explain me about "self". Is it a keyword?

Frank Wed, 24 Feb 2016

self is not a keyword. You can use self.x to access the object attribute x inside a class.

For illustration, if you have an object named car with a variable name, you can access the attribute with self.name inside the class methods. The statements in the class methods will be applied to all variables of newly created objects. If we define self.driver = 'Shiney', all newly created objects will have a driver named Shiney. To set a variable for a single object you would use instanceName.driver = x or instanceName.setDriver(x)

Miguel Tue, 01 Mar 2016

Hello!

I don't understand yet the word "self". In the following example, the code didn't work until I put the word "self" on the argument of the function "Imprimir"


class myAccount:
name = ""
SavedMoney = 0
bills = 0
deposits = 0
def __init__(self, name, midinero, bills, deposits):
self.name = name
self.SavedMoney = midinero
self.bills = bills
self.deposits = deposits
def addMoney (self, amount):
self.SavedMoney = self.SavedMoney + amount
def Imprimir(self):
print self.name
micuenta = myAccount("Miguel", 200, 0, 0)
micuenta.Imprimir()

why do I have to take "self" as argument in every function?

Frank Wed, 02 Mar 2016

Without using the self keyword you are using local variables. Local variables cannot be accessed outside the functions, because of the scope of the variable.

For illustration, consider this code:


def __init__(self, name, midinero, bills, deposits):
self.name = name
self.SavedMoney = midinero
self.bills = bills
self.deposits = deposits
onlyInScope = 3

The variable onlyInScope can only be accessed within __init__(). Adding the self keyword makes them accessibly outside by newly created objects. Adding self will tell Python these are class variables.