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. Shiney
    - February 24, 2016

    Please explain me about “self”. Is it a keyword?

    1. Frank
      - February 24, 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)

      1. Marc Hankin
        - January 28, 2018

        I don’t understand the “instanceName.setDriver(x)”
        When I tried running:
        micuenta.setDriver(x)
        it produced the following error message:
        AttributeError: myAccount instance has no attribute ‘setDriver’



        But thank you so much for this wonderful tutorial. It is very helpful.

        1. Frank
          - January 29, 2018

          Thanks Marc! The error means the method setDriver doesn’t exist in the class.
          Create the method setDriver() inside the class.

          class myAccount:
          name = ""
            def setDriver(self, name):
          self.name = name
           user1 = myAccount()
          user1.setDriver('Marc')
          print(user1.name)

  2. Hina
    - January 5, 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()

    1. Frank
      - January 8, 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.

  3. Sumit
    - December 21, 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

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

  4. Sadia
    - December 20, 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()

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

      1. Sadia
        - December 29, 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))

        1. Frank
          - December 31, 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().

  5. Sadia
    - December 17, 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()

    1. Frank
      - December 19, 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)

  6. Ravali
    - November 16, 2015

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

    1. Frank
      - November 16, 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.

Leave a Reply

Login disabled