Python Objects and Classes

Slides:



Advertisements
Similar presentations
Final and Abstract Classes
Advertisements

1 Inheritance Classes and Subclasses Or Extending a Class.
Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Python Mini-Course University of Oklahoma Department of Psychology Lesson 28 Classes and Methods 6/17/09 Python Mini-Course: Lesson 28 1.
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Inheritance Inheritance Reserved word protected Reserved word super
Inheritance Java permits you to use your user defined classes to create programs using inheritance.
Object-Oriented PHP (1)
Road Map Introduction to object oriented programming. Classes
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
Python 3 Some material adapted from Upenn cis391 slides and other sources.
Guide to Programming with Python
Python 3 Some material adapted from Upenn cis391 slides and other sources.
OOP Languages: Java vs C++
Python Crash Course Classes 3 rd year Bachelors V1.0 dd Hour 7.
Unit 5 School of Information Systems & Technology1 School of Information Systems and Technology (IST)
1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Chapter 8 More Object Concepts
1 Understanding Inheritance COSC 156 C++ Programming Lecture 8.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Python: Classes By Matt Wufsus. Scopes and Namespaces A namespace is a mapping from names to objects. ◦Examples: the set of built-in names, such as the.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Introduction to Python III CSE-391: Artificial Intelligence University of Pennsylvania Matt Huenerfauth January 2005.
OOP IN PHP `Object Oriented Programming in any language is the use of objects to represent functional parts of an application and real life entities. For.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
Parameters… Classes Cont Mrs. C. Furman October 13, 2008.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Programming in Java CSCI-2220 Object Oriented Programming.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
1 Chapter Four Creating and Using Classes. 2 Objectives Learn about class concepts How to create a class from which objects can be instantiated Learn.
Introduction to Python III CIS 391: Artificial Intelligence Fall, 2008.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
 Objects versus Class  Three main concepts of OOP ◦ Encapsulation ◦ Inheritance ◦ Polymorphism  Method ◦ Parameterized ◦ Value-Returning.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Object-Oriented Programming (OOP) What we did was: (Procedural Programming) a logical procedure that takes input data, processes it, and produces output.
Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.
Classes, Interfaces and Packages
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
CSCI/CMPE 4341 Topic: Programming in Python Chapter 7: Introduction to Object- Oriented Programming in Python – Exercises Xiang Lian The University of.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
CMSC201 Computer Science I for Majors Lecture 25 – Classes
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
OOP: Encapsulation &Abstraction
Python 3 Some material adapted from Upenn cis391 slides and other sources.
Object Oriented Programming in Python: Defining Classes
Inheritance and Polymorphism
Creating and Deleting Instances Access to Attributes and Methods
Understanding Inheritance
Corresponds with Chapter 7
Java Programming Language
CISC/CMPE320 - Prof. McLeod
Object-Oriented Programming
Final and Abstract Classes
Presentation transcript:

Python Objects and Classes

Over view of OOPS Class: A user-defined prototype for an object that defines a set of attributes that characterize any object of the class. The attributes are data members (class variables and instance variables) and methods, accessed via dot notation. Data member: A class variable or instance variable that holds data associated with a class and its objects. Function overloading: The assignment of more than one behavior to a particular function. The operation performed varies by the types of objects (arguments) involved. Inheritance : The transfer of the characteristics of a class to other classes that are derived from it. Instance: An individual object of a certain class. An object obj that belongs to a class Circle, for example, is an instance of the class Circle. Method : A special kind of function that is defined in a class definition. Object : A unique instance of a data structure that's defined by its class. An object comprises both data members (class variables and instance variables) and methods. Operator overloading: The assignment of more than one function to a particular operator.

Defining a Class A class is a special data type which defines how to build a certain kind of object. The ‘class’ also stores some data items that are shared by all the instances of this class. ‘Instances’ are objects that are created which follow the definition given inside of the class. Python doesn’t use separate class interface definitions as in some languages. You just define the class and then use it.

Methods in Classes You can define a method in a class by including function definitions within the scope of the class block. Note that there is a special first argument self in all of the method definitions. Note that there is usually a special method called __init__ in most classes.

Definition of student class class student: “““A class representing a student.””” def __init__(self,n,a): self.full_name = n self.age = a def get_age(self): return self.age

Instantiating Objects There is no “new” keyword as in Java. You merely use the class name with () notation and assign the result to a variable. b = student(“Bob Smith”, 21) The arguments you pass to the class name are actually given to its .__init__() method.

Constructor: __init__ __init__ acts like a constructor for your class. When you create a new instance of a class, this method is invoked. Usually does some initialization work. The arguments you list when instantiating an instance of the class are passed along to the __init__ method. b = student(“Bob”, 21) So, the __init__ method is passed “Bob” and 21.

Constructor: __init__ Your __init__ method can take any number of arguments. Just like other functions or methods, the arguments can be defined with default values, making them optional to the caller. However, the first argument self in the definition of __init__ is special…

Self The first argument of every method is a reference to the current instance of the class. By convention, we name this argument self. In __init__, self refers to the object currently being created; so, in other class methods, it refers to the instance whose method was called. Similar to the keyword ‘this’ in Java or C++. But Python uses ‘self’ more often than Java uses ‘this.’

Self Although you must specify self explicitly when defining the method, you don’t include it when calling the method. Python passes it for you automatically. Defining a method: Calling a method: (this code inside a class definition.) def set_age(self, num): >>> x.set_age(23) self.age = num

No Need to “free” When you are done with an object, you don’t have to delete or free it explicitly. Python has automatic garbage collection. Python will automatically detect when all of the references to a piece of memory have gone out of scope. Automatically frees that memory. Generally works well, few memory leaks.

__del__ method Class can implement the special method __del__(), called a destructor, that is invoked when the instance is about to be destroyed. This method might be used to clean up any nonmemory resources used by an instance.

Access to Attributes and Methods >>> f = student (“Bob Smith”, 23) >>> f.full_name # Access an attribute. “Bob Smith” >>> f.get_age() # Access a method. 23

Accessing unknown members What if you don’t know the name of the attribute or method of a class that you want to access until run time… Is there a way to take a string containing the name of an attribute or method of a class and get a reference to it (so you can use it)?

getattr(object_instance, string) >>> f = student(“Bob Smith”, 23) >>> getattr(f, “full_name”) “Bob Smith” >>> getattr(f, “get_age”) <method get_age of class studentClass at 010B3C2> >>> getattr(f, “get_age”)() # We can call this. 23 >>> getattr(f, “get_birthday”) # Raises AttributeError – No method exists.

hasattr(object_instance,string) >>> f = student(“Bob Smith”, 23) >>> hasattr(f, "full_name") True >>> hasattr(f, "get_age") >>> hasattr(f, "get_birthday") False

Two Kinds of Attributes The non-method data stored by objects are called attributes. There’s two kinds: Data attribute: Variable owned by a particular instance of a class. Each instance can have its own different value for it. These are the most common kind of attribute. Class attributes: Owned by the class as a whole. All instances of the class share the same value for it. Called “static” variables in some languages. Good for class-wide constants or for building counter of how many instances of the class have been made.

Data Attributes You create and initialize a data attribute inside of the __init__() method. Remember assignment is how we create variables in Python; so, assigning to a name creates the attribute. Inside the class, you refer to data attributes using self – for example, self.full_name class teacher: “A class representing teachers.” def __init__(self,n): self.full_name = n def print_name(self): print self.full_name

Class Attributes All instances of a class share one copy of a class attribute, so when any of the instances change it, then the value is changed for all of them. We define class attributes outside of any method. Since there is one of these attributes per class and not one per instance, we use a different notation: We access them using self.__class__.name notation. class sample: >>> a = sample() x = 23 >>> a.increment() def increment(self): >>> a.__class__.x self.__class__.x += 1 24

Data vs. Class Attributes class counter: overall_total = 0 # class attribute def __init__(self): self.my_total = 0 # data attribute def increment(self): counter.overall_total = \ counter.overall_total + 1 self.my_total = \ self.my_total + 1 >>> a = counter() >>> b = counter() >>> a.increment() >>> b.increment() >>> b.increment() >>> a.my_total 1 >>> a.__class__.overall_total 3 >>> b.my_total 2 >>> b.__class__.overall_total 3

Data Hiding Any attribute or method with two leading underscores in its name (but none at the end) is private. It cannot be accessed outside of that class. Note-1: Names with two underscores at the beginning and the end are for built-in methods or attributes for the class. Note-2: There is no ‘protected’ status in Python; so, subclasses would be unable to access these private data either.

Example

Inheritance(Subclasses) A class can extend the definition of another class in order to use (or redefine) methods and attributes already defined in the previous one. New class: “subclass.” Original: “parent” or “ancestor.” When defining a subclass, you put the name of the parent in parentheses after the subclass’s name on the first line of the definition. class ai_student(student): Python has no ‘extends’ keyword like Java. Multiple inheritance is supported.

Inheritance class ai_student (student): “A class extending student.” def __init__(self,n,a,s): student.__init__(self,n,a) self.section_num = s def get_age(self): print “Age: ” + str(self.age) ais1= ai_student("aaa",20,"a") ais1.get_age() class student: “A class representing a student.” def __init__(self,n,a): self.full_name = n self.age = a def get_age(self): return self.age Output 20

: Built-In Class Attributes

You can use issubclass() or isinstance() functions to check a relationships of two classes and instances: The issubclass(sub, sup) boolean function returns true if the given subclass sub is indeed a subclass of the superclass sup. The isinstance(obj, Class) boolean function returns true if obj is an instance of class Class or is an instance of a subclass of Class

Overriding Methods: You can always override your parent class methods. One reason for overriding parent's methods is because you may want special or different functionality in your subclass

Overloading Operators:

Exercises Write code to create an instance of this class and set its attributes: class Dog(): age = 0 name = "" weight = 0 Write code to create two different instances of this class and set attributes for both objects: class Person(): cellPhone = "" email = ""

Exercises For the code below, write a class that has the appropriate class name and attributes that will allow the code to work. myBird = Bird() myBird.color = "green" myBird.name = "Sunny" myBird.breed = "Sun Conure" Develop a program that calculate class average for each of the three tests for a class of 20 students and the program should also calculate the average of each of the student scores in those three test. Should also display the results in descending order per test i.e a student name and the corresponding test result of the student.

Exercises Write a python program to implement the following Employee Clerk Software Engineer Team Leader

Exercises Write a class called Mylist that shadows a python list: it should overload + operator to append the data to the list. Also provide constructor for your class that takes an existing list. Create a class called time. Its three members all type int should be called hours, minutes and seconds. Write a program that prompts the user to enter a time values separately. The Program should then store the time in the object and finally printout the total no of seconds represented by this value. Use appropriate member functions. Develop python program to compute the area of geometrical objects and display the computed area.