logo

Python class: Objects and classes

Introduction


Technology always evolves. What are classes and where do they come from?

1. Statements:
In the very early days of computing, programmers wrote only commands.

2. Functions:
Reusable group of statements, helped to structure that code and it improved readability.

3. Classes:
Classes are used to create objects which have functions and variables. Strings are examples of objects: A string book has the functions book.replace() and book.lowercase(). This style is often called object oriented programming.

Lets take a dive!

Python Courses:
Python Programming Bootcamp: Go from zero to hero

Python class


We can create virtual objects in Python. A virtual object can contain variables and methods.  A program may have many different types and are created from a class. Example:

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()

Run this program. In this code we have 3 virtual objects: james, david and eric.  Each object is instance of the User class.

python class: creation of objects Python Class: create objects

In this class we defined the sayHello() method, which is why we can call it for each of the objects.  The init() method is called the constructor and is always called when creating an object.  The variables owned by the class is in this case “name”. These variables are sometimes called class attributes.

We can create methods in classes which update the internal variables of the object. This may sound vague but I will demonstrate with an example.

Class variables


We define a class CoffeeMachine of which the virtual objects hold the amount of beans and amount of water. Both are defined as a number (integer). We may then define methods that add or remove beans.

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

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

We do the same for the variable water. As shown below:

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()

Run this program. The top of the code defines the class as we described.  The code below is where we create virtual objects. In this example we have exactly one object called “pythonBean”.  We then call methods which change the internal variables, this is possible because we defined those methods inside the class.  Output:


Name = Python Bean
Beans = 83
Water = 20

Name = Python Bean
Beans = 84
Water = 20

Download Exercises
 

BackNext

60 thoughts on “Python class: Objects and classes


  1. Than
    - September 10, 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

    1. Frank
      - September 10, 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!

  2. Ben
    - August 26, 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

    1. Frank
      - August 26, 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.

  3. Saqib Ali Khan
    - August 25, 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

    1. Frank
      - August 25, 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

  4. Radu
    - August 22, 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

    1. Frank
      - August 22, 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()

      1. Radu
        - August 22, 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!

        1. Frank
          - August 22, 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

          1. Radu
            - August 22, 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.

  5. Ben
    - August 21, 2015

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

    1. Frank
      - August 21, 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.

  6. James Thangjam
    - August 20, 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

    1. Frank
      - August 20, 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

Leave a Reply

Login disabled