LN 10 ObjectNClass
LN 10 ObjectNClass
PROGRAMMING PARADIGM
Script Programming with Python
Source: http://www.trytoprogram.com/python-programming/python-object-and-class/
5
Built-in Class
• Python has several built-in class including
• String
• Lists
• Dictionary
• and so on
• For example, a String class that makes string objects such as ‘cat’
and ‘dog’
User-defined Class
• When you write a class
• You defined the general behaviour of whole category of objects can
have
• Classes can be
• Typed directly into programs
• Stored in modules and brought into programs with an import
statement
7
Each instance created from the Dog class will store a name and an age, and
each dog will have the ability to sit() and roll_over():
8
The self parameter is required as the first parameter in the method definition.
Each method's self parameter references the object; it gives the individual
instance access to the attributes and methods in the class.
4• The two variable defined have the prefix self. Any variable prefixed with self is
available to every method in the class, and also accessible through any
instance created from the class. These variables are called attributes.
9
1
2
1• Tell Python to create a dog name ‘willie’ age 6 in the variable my_dog. When
Python reads this line, it calls the __init__() method to creates an instance
representing this particular dog and sets the name and age attributes using
the values provided.
• To call a method, give the name of the instance (in this case, my_dog) and the
method you want to call, separated by a dot. When Python reads my_dog.sit(),
it looks for the method sit() in the class Dog and runs that code.
12
• Each dog is a separate instance with its own set of attributes, capable of the
same set of actions.
13
Hands-on Activities
• Make a class called User. Create two attributes called first_name and
last_name, and then create several other attributes that are typically
stored in a user profile. Make a method called describe_user() that
prints a summary of the user’s information. Make another method
called greet_user() that prints a personalized greeting to the user.