This document provides an introduction to object-oriented programming in Python. It discusses how everything in Python is an object with a type, and how to create new object types using classes. Key points covered include defining classes with attributes like __init__() and methods, creating instances of classes, and defining special methods like __str__() to customize object behavior and representations. The document uses examples like Coordinate and Fraction classes to illustrate how to implement and use custom object types in Python.
The document discusses key concepts of object-oriented programming such as classes, objects, encapsulation, inheritance, and polymorphism. It provides examples of defining a Point class in Python with methods like translate() and distance() as well as using concepts like constructors, private and protected members, and naming conventions using underscores. The document serves as an introduction to object-oriented programming principles and their implementation in Python.
Python supports object-oriented programming through classes, objects, and related concepts like inheritance, polymorphism, and encapsulation. A class acts as a blueprint to create object instances. Objects contain data fields and methods. Inheritance allows classes to inherit attributes and behaviors from parent classes. Polymorphism enables the same interface to work with objects of different types. Encapsulation helps protect data by restricting access.
Class, object and inheritance in pythonSantosh Verma
The document discusses object-oriented programming concepts in Python, including classes, objects, methods, inheritance, and the built-in __init__ method. Classes are created using the class keyword and contain attributes and methods. Methods must have a self parameter, which refers to the instance of the class. The __init__ method is similar to a constructor and is called when an object is instantiated. Inheritance allows one class to inherit attributes and methods from another class.
Creating Objects in Python. For more detail see:
http://www.damiantgordon.com/Videos/ProgrammingAndAlgorithms/MainMenu.html
The document discusses object-oriented programming concepts in Python including classes, objects, methods, and class definitions. Some key points:
- Python supports object-oriented programming with classes that define new data types and objects that are instances of those classes.
- A class defines attributes and methods that are common to all objects of that class. Methods are functions defined inside classes that operate on object instances.
- Objects are instantiated from classes and can have instance-specific attribute values. Dot notation accesses attributes and methods of an object.
- Initialization methods like __init__() set up new object instances. Special methods starting with double underscores have predefined meanings.
- Methods allow passing the object instance as the first
This document provides an overview of object-oriented programming concepts in Python including objects, classes, inheritance, polymorphism, and encapsulation. It defines key terms like objects, classes, and methods. It explains how to create classes and objects in Python. It also discusses special methods, modules, and the __name__ variable.
This document discusses object-oriented programming concepts in Python including classes, objects, attributes, methods, inheritance, and method overriding. It defines a MyVector class with x and y attributes and methods to add vectors and display their count. Access specifiers like private and built-in are covered. Python uses garbage collection and has no destructors. Inheritance allows a SubVector class to extend MyVector, and a method can be overridden to change a class's behavior.
This document discusses object-oriented programming concepts in Python including:
- Classes define templates for objects with attributes and methods. Objects are instances of classes.
- The __init__ method initializes attributes when an object is constructed.
- Classes can make attributes private using double underscores. Encapsulation hides implementation details.
- Objects can be mutable, allowing state changes, or immutable like strings which cannot change.
- Inheritance allows subclasses to extend and modify parent class behavior through polymorphism.
The document discusses classes and objects in Python programming. It covers key concepts like defining classes, creating objects, assigning attributes to objects, passing objects as arguments and returning objects from functions. It provides examples to illustrate these concepts like defining a Point class to represent coordinate points, creating Rectangle class with a Point object as one of its attributes. The document also discusses concepts like aliasing of objects and how to create a copy of an object instead of alias.
This document provides an overview of object-oriented programming concepts including classes, objects, encapsulation and abstraction. It begins by describing the objectives of learning OOP which are to describe objects and classes, define classes, construct objects using constructors, access object members using dot notation, and apply abstraction and encapsulation. It then compares procedural and object-oriented programming, noting that OOP involves programming using objects defined by classes. Key concepts covered include an object's state consisting of data fields and behavior defined by methods. The document demonstrates defining classes, creating objects, accessing object members, and using private data fields for encapsulation.
This document provides an introduction to object oriented programming in Python. It discusses key OOP concepts like classes, methods, encapsulation, abstraction, inheritance, polymorphism, and more. Each concept is explained in 1-2 paragraphs with examples provided in Python code snippets. The document is presented as a slideshow that is meant to be shared and provide instruction on OOP in Python.
- The document introduces the CSC148 course, which covers object-oriented programming principles, recursive functions and data structures, algorithm efficiency, and sorting algorithms.
- Students will be evaluated based on labs, assignments, term tests, and a final exam. The final exam must be passed for a student to pass the course.
- Lectures will introduce new material and have worksheets, labs are done in pairs, assignments are individual or with 1-2 partners and cannot be submitted late.
- The document provides examples of Python objects like strings and turtles, and discusses classes, methods, attributes, inheritance and more OO concepts.
Python allows importing and using classes and functions defined in other files through modules. There are three main ways to import modules: import somefile imports everything and requires prefixing names with the module name, from somefile import * imports everything without prefixes, and from somefile import className imports a specific class. Modules look for files in directories listed in sys.path.
Classes define custom data types by storing shared data and methods. Instances are created using class() and initialized with __init__. Self refers to the instance inside methods. Attributes store an instance's data while class attributes are shared. Inheritance allows subclasses to extend and redefine parent class features. Special built-in methods control class behaviors like string representation or iteration.
The document discusses various advanced Python concepts including classes, exception handling, generators, CGI, databases, Tkinter for GUI, regular expressions, and email sending using SMTP. It covers object-oriented programming principles like inheritance, encapsulation, and polymorphism in Python. Specific Python concepts like creating and accessing class attributes, instantiating objects, method overloading, operator overloading, and inheritance are explained through examples. The document also discusses generator functions and expressions for creating iterators in Python in a memory efficient way.
This document discusses Python modules, classes, inheritance, and properties. Some key points:
- Modules allow the organization of Python code into reusable libraries by saving code in files with a .py extension. Modules can contain functions, variables, and be imported into other code.
- Classes are templates that define the properties and methods common to all objects of a certain kind. The __init__() method initializes new objects. Inheritance allows child classes to inherit properties and methods from parent classes.
- Properties provide a way to control access to class attributes, allowing them to be accessed like attributes while hiding the implementation details behind getter and setter methods.
Python: Migrating from Procedural to Object-Oriented ProgrammingDamian T. Gordon
The document discusses migrating code to an object-oriented approach. It begins with an example of modeling polygons with points and calculating perimeters procedurally. It then shows how to model this using classes to encapsulate the Point and Polygon logic and attributes. The document also discusses using properties to add behavior when getting and setting attributes, like validation checks. Properties allow interacting with attributes through getter and setter methods while retaining the attribute syntax.
Object oriented programming with pythonArslan Arshad
A short intro to how Object Oriented Paradigm work in Python Programming language. This presentation created for beginner like bachelor student of Computer Science.
Build enterprise-ready applications using skills you already have!PhilMeredith3
Process Tempo is a rapid application development (RAD) environment that empowers data teams to create enterprise-ready applications using skills they already have.
With Process Tempo, data teams can craft beautiful, pixel-perfect applications the business will love.
Process Tempo combines features found in business intelligence tools, graphic design tools and workflow solutions - all in a single platform.
Process Tempo works with all major databases such as Databricks, Snowflake, Postgres and MySQL. It also works with leading graph database technologies such as Neo4j, Puppy Graph and Memgraph.
It is the perfect platform to accelerate the delivery of data-driven solutions.
For more information, you can find us at www.processtempo.com
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...WSO2
Enterprises must deliver intelligent, cloud native applications quickly—without compromising governance or scalability. This session explores how an internal developer platform increases productivity via AI for code and accelerates AI-native app delivery via code for AI. Learn practical techniques for embedding AI in the software lifecycle, automating governance with AI agents, and applying a cell-based architecture for modularity and scalability. Real-world examples and proven patterns will illustrate how to simplify delivery, enhance developer productivity, and drive measurable outcomes.
Learn more: https://wso2.com/choreo
More Related Content
Similar to Python - Classes and Objects, Inheritance (20)
The document discusses object-oriented programming concepts in Python including classes, objects, methods, and class definitions. Some key points:
- Python supports object-oriented programming with classes that define new data types and objects that are instances of those classes.
- A class defines attributes and methods that are common to all objects of that class. Methods are functions defined inside classes that operate on object instances.
- Objects are instantiated from classes and can have instance-specific attribute values. Dot notation accesses attributes and methods of an object.
- Initialization methods like __init__() set up new object instances. Special methods starting with double underscores have predefined meanings.
- Methods allow passing the object instance as the first
This document provides an overview of object-oriented programming concepts in Python including objects, classes, inheritance, polymorphism, and encapsulation. It defines key terms like objects, classes, and methods. It explains how to create classes and objects in Python. It also discusses special methods, modules, and the __name__ variable.
This document discusses object-oriented programming concepts in Python including classes, objects, attributes, methods, inheritance, and method overriding. It defines a MyVector class with x and y attributes and methods to add vectors and display their count. Access specifiers like private and built-in are covered. Python uses garbage collection and has no destructors. Inheritance allows a SubVector class to extend MyVector, and a method can be overridden to change a class's behavior.
This document discusses object-oriented programming concepts in Python including:
- Classes define templates for objects with attributes and methods. Objects are instances of classes.
- The __init__ method initializes attributes when an object is constructed.
- Classes can make attributes private using double underscores. Encapsulation hides implementation details.
- Objects can be mutable, allowing state changes, or immutable like strings which cannot change.
- Inheritance allows subclasses to extend and modify parent class behavior through polymorphism.
The document discusses classes and objects in Python programming. It covers key concepts like defining classes, creating objects, assigning attributes to objects, passing objects as arguments and returning objects from functions. It provides examples to illustrate these concepts like defining a Point class to represent coordinate points, creating Rectangle class with a Point object as one of its attributes. The document also discusses concepts like aliasing of objects and how to create a copy of an object instead of alias.
This document provides an overview of object-oriented programming concepts including classes, objects, encapsulation and abstraction. It begins by describing the objectives of learning OOP which are to describe objects and classes, define classes, construct objects using constructors, access object members using dot notation, and apply abstraction and encapsulation. It then compares procedural and object-oriented programming, noting that OOP involves programming using objects defined by classes. Key concepts covered include an object's state consisting of data fields and behavior defined by methods. The document demonstrates defining classes, creating objects, accessing object members, and using private data fields for encapsulation.
This document provides an introduction to object oriented programming in Python. It discusses key OOP concepts like classes, methods, encapsulation, abstraction, inheritance, polymorphism, and more. Each concept is explained in 1-2 paragraphs with examples provided in Python code snippets. The document is presented as a slideshow that is meant to be shared and provide instruction on OOP in Python.
- The document introduces the CSC148 course, which covers object-oriented programming principles, recursive functions and data structures, algorithm efficiency, and sorting algorithms.
- Students will be evaluated based on labs, assignments, term tests, and a final exam. The final exam must be passed for a student to pass the course.
- Lectures will introduce new material and have worksheets, labs are done in pairs, assignments are individual or with 1-2 partners and cannot be submitted late.
- The document provides examples of Python objects like strings and turtles, and discusses classes, methods, attributes, inheritance and more OO concepts.
Python allows importing and using classes and functions defined in other files through modules. There are three main ways to import modules: import somefile imports everything and requires prefixing names with the module name, from somefile import * imports everything without prefixes, and from somefile import className imports a specific class. Modules look for files in directories listed in sys.path.
Classes define custom data types by storing shared data and methods. Instances are created using class() and initialized with __init__. Self refers to the instance inside methods. Attributes store an instance's data while class attributes are shared. Inheritance allows subclasses to extend and redefine parent class features. Special built-in methods control class behaviors like string representation or iteration.
The document discusses various advanced Python concepts including classes, exception handling, generators, CGI, databases, Tkinter for GUI, regular expressions, and email sending using SMTP. It covers object-oriented programming principles like inheritance, encapsulation, and polymorphism in Python. Specific Python concepts like creating and accessing class attributes, instantiating objects, method overloading, operator overloading, and inheritance are explained through examples. The document also discusses generator functions and expressions for creating iterators in Python in a memory efficient way.
This document discusses Python modules, classes, inheritance, and properties. Some key points:
- Modules allow the organization of Python code into reusable libraries by saving code in files with a .py extension. Modules can contain functions, variables, and be imported into other code.
- Classes are templates that define the properties and methods common to all objects of a certain kind. The __init__() method initializes new objects. Inheritance allows child classes to inherit properties and methods from parent classes.
- Properties provide a way to control access to class attributes, allowing them to be accessed like attributes while hiding the implementation details behind getter and setter methods.
Python: Migrating from Procedural to Object-Oriented ProgrammingDamian T. Gordon
The document discusses migrating code to an object-oriented approach. It begins with an example of modeling polygons with points and calculating perimeters procedurally. It then shows how to model this using classes to encapsulate the Point and Polygon logic and attributes. The document also discusses using properties to add behavior when getting and setting attributes, like validation checks. Properties allow interacting with attributes through getter and setter methods while retaining the attribute syntax.
Object oriented programming with pythonArslan Arshad
A short intro to how Object Oriented Paradigm work in Python Programming language. This presentation created for beginner like bachelor student of Computer Science.
Build enterprise-ready applications using skills you already have!PhilMeredith3
Process Tempo is a rapid application development (RAD) environment that empowers data teams to create enterprise-ready applications using skills they already have.
With Process Tempo, data teams can craft beautiful, pixel-perfect applications the business will love.
Process Tempo combines features found in business intelligence tools, graphic design tools and workflow solutions - all in a single platform.
Process Tempo works with all major databases such as Databricks, Snowflake, Postgres and MySQL. It also works with leading graph database technologies such as Neo4j, Puppy Graph and Memgraph.
It is the perfect platform to accelerate the delivery of data-driven solutions.
For more information, you can find us at www.processtempo.com
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...WSO2
Enterprises must deliver intelligent, cloud native applications quickly—without compromising governance or scalability. This session explores how an internal developer platform increases productivity via AI for code and accelerates AI-native app delivery via code for AI. Learn practical techniques for embedding AI in the software lifecycle, automating governance with AI agents, and applying a cell-based architecture for modularity and scalability. Real-world examples and proven patterns will illustrate how to simplify delivery, enhance developer productivity, and drive measurable outcomes.
Learn more: https://wso2.com/choreo
The rise of e-commerce has redefined how retailers operate—and reconciliation...Prachi Desai
As payment flows grow more fragmented, the complexity of reconciliation and revenue recognition increases. The result? Mounting operational costs, silent revenue leakages, and avoidable financial risk.
Spot the inefficiencies. Automate what’s slowing you down.
https://www.taxilla.com/ecommerce-reconciliation
How to purchase, license and subscribe to Microsoft Azure_PDF.pdfvictordsane
Microsoft Azure is a cloud platform that empowers businesses with scalable computing, data analytics, artificial intelligence, and cybersecurity capabilities.
Arguably the biggest hurdle for most organizations is understanding how to get started.
Microsoft Azure is a consumption-based cloud service. This means you pay for what you use. Unlike traditional software, Azure resources (e.g., VMs, databases, storage) are billed based on usage time, storage size, data transfer, or resource configurations.
There are three primary Azure purchasing models:
• Pay-As-You-Go (PAYG): Ideal for flexibility. Billed monthly based on actual usage.
• Azure Reserved Instances (RI): Commit to 1- or 3-year terms for predictable workloads. This model offers up to 72% cost savings.
• Enterprise Agreements (EA): Best suited for large organizations needing comprehensive Azure solutions and custom pricing.
Licensing Azure: What You Need to Know
Azure doesn’t follow the traditional “per seat” licensing model. Instead, you pay for:
• Compute Hours (e.g., Virtual Machines)
• Storage Used (e.g., Blob, File, Disk)
• Database Transactions
• Data Transfer (Outbound)
Purchasing and subscribing to Microsoft Azure is more than a transactional step, it’s a strategic move.
Get in touch with our team of licensing experts via [email protected] to further understand the purchasing paths, licensing options, and cost management tools, to optimize your investment.
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...Insurance Tech Services
A modern Policy Administration System streamlines workflows and integrates with core systems to boost speed, accuracy, and customer satisfaction across the policy lifecycle. Visit https://www.damcogroup.com/insurance/policy-administration-systems for more details!
Artificial Intelligence Applications Across IndustriesSandeepKS52
Artificial Intelligence is a rapidly growing field that influences many aspects of modern life, including transportation, healthcare, and finance. Understanding the basics of AI provides insight into how machines can learn and make decisions, which is essential for grasping its applications in various industries. In the automotive sector, AI enhances vehicle safety and efficiency through advanced technologies like self-driving systems and predictive maintenance. Similarly, in healthcare, AI plays a crucial role in diagnosing diseases and personalizing treatment plans, while in financial services, it helps in fraud detection and risk management. By exploring these themes, a clearer picture of AI's transformative impact on society emerges, highlighting both its potential benefits and challenges.
How AI Can Improve Media Quality Testing Across Platforms (1).pptxkalichargn70th171
Media platforms, from video streaming to OTT and Smart TV apps, face unprecedented pressure to deliver seamless, high-quality experiences across diverse devices and networks. Ensuring top-notch Quality of Experience (QoE) is critical for user satisfaction and retention.
FME as an Orchestration Tool - Peak of Data & AI 2025Safe Software
Processing huge amounts of data through FME can have performance consequences, but as an orchestration tool, FME is brilliant! We'll take a look at the principles of data gravity, best practices, pros, cons, tips and tricks. And of course all spiced up with relevant examples!
Bonk coin airdrop_ Everything You Need to Know.pdfHerond Labs
The Bonk airdrop, one of the largest in Solana’s history, distributed 50% of its total supply to community members, significantly boosting its popularity and Solana’s network activity. Below is everything you need to know about the Bonk coin airdrop, including its history, eligibility, how to claim tokens, risks, and current status.
https://blog.herond.org/bonk-coin-airdrop/
Design by Contract - Building Robust Software with Contract-First DevelopmentPar-Tec S.p.A.
In the fast-paced world of software development, code quality and reliability are paramount. This SlideShare deck, presented at PyCon Italia 2025 by Antonio Spadaro, DevOps Engineer at Par-Tec, introduces the “Design by Contract” (DbC) philosophy and demonstrates how a Contract-First Development approach can elevate your projects.
Beginning with core DbC principles—preconditions, postconditions, and invariants—these slides define how formal “contracts” between classes and components lead to clearer, more maintainable code. You’ll explore:
The fundamental concepts of Design by Contract and why they matter.
How to write and enforce interface contracts to catch errors early.
Real-world examples showcasing how Contract-First Development improves error handling, documentation, and testability.
Practical Python demonstrations using libraries and tools that streamline DbC adoption in your workflow.
Alt-lenders are scaling fast, but manual loan reconciliation is cracking under pressure. See how automation solves revenue leakage and compliance chaos.
https://www.taxilla.com/loan-repayment-reconciliation
Insurance policy management software transforms complex, manual insurance operations into streamlined, efficient digital workflows, enhancing productivity, accuracy, customer service, and profitability for insurers. Visit https://www.damcogroup.com/insurance/policy-management-software for more details!
Best Inbound Call Tracking Software for Small BusinessesTheTelephony
The best inbound call tracking software for small businesses offers features like call recording, real-time analytics, lead attribution, and CRM integration. It helps track marketing campaign performance, improve customer service, and manage leads efficiently. Look for solutions with user-friendly dashboards, customizable reporting, and scalable pricing plans tailored for small teams. Choosing the right tool can significantly enhance communication and boost overall business growth.
Generative Artificial Intelligence and its ApplicationsSandeepKS52
The exploration of generative AI begins with an overview of its fundamental concepts, highlighting how these technologies create new content and ideas by learning from existing data. Following this, the focus shifts to the processes involved in training and fine-tuning models, which are essential for enhancing their performance and ensuring they meet specific needs. Finally, the importance of responsible AI practices is emphasized, addressing ethical considerations and the impact of AI on society, which are crucial for developing systems that are not only effective but also beneficial and fair.
FME for Climate Data: Turning Big Data into Actionable InsightsSafe Software
Regional and local governments aim to provide essential services for stormwater management systems. However, rapid urbanization and the increasing impacts of climate change are putting growing pressure on these governments to identify stormwater needs and develop effective plans. To address these challenges, GHD developed an FME solution to process over 20 years of rainfall data from rain gauges and USGS radar datasets. This solution extracts, organizes, and analyzes Next Generation Weather Radar (NEXRAD) big data, validates it with other data sources, and produces Intensity Duration Frequency (IDF) curves and future climate projections tailored to local needs. This presentation will showcase how FME can be leveraged to manage big data and prioritize infrastructure investments.
Plooma is a writing platform to plan, write, and shape books your wayPlooma
Plooma is your all in one writing companion, designed to support authors at every twist and turn of the book creation journey. Whether you're sketching out your story's blueprint, breathing life into characters, or crafting chapters, Plooma provides a seamless space to organize all your ideas and materials without the overwhelm. Its intuitive interface makes building rich narratives and immersive worlds feel effortless.
Packed with powerful story and character organization tools, Plooma lets you track character development and manage world building details with ease. When it’s time to write, the distraction-free mode offers a clean, minimal environment to help you dive deep and write consistently. Plus, built-in editing tools catch grammar slips and style quirks in real-time, polishing your story so you don’t have to juggle multiple apps.
What really sets Plooma apart is its smart AI assistant - analyzing chapters for continuity, helping you generate character portraits, and flagging inconsistencies to keep your story tight and cohesive. This clever support saves you time and builds confidence, especially during those complex, detail packed projects.
Getting started is simple: outline your story’s structure and key characters with Plooma’s user-friendly planning tools, then write your chapters in the focused editor, using analytics to shape your words. Throughout your journey, Plooma’s AI offers helpful feedback and suggestions, guiding you toward a polished, well-crafted book ready to share with the world.
With Plooma by your side, you get a powerful toolkit that simplifies the creative process, boosts your productivity, and elevates your writing - making the path from idea to finished book smoother, more fun, and totally doable.
Get Started here: https://www.plooma.ink/
Agentic Techniques in Retrieval-Augmented Generation with Azure AI SearchMaxim Salnikov
Discover how Agentic Retrieval in Azure AI Search takes Retrieval-Augmented Generation (RAG) to the next level by intelligently breaking down complex queries, leveraging full conversation history, and executing parallel searches through a new LLM-powered query planner. This session introduces a cutting-edge approach that delivers significantly more accurate, relevant, and grounded answers—unlocking new capabilities for building smarter, more responsive generative AI applications.
Traditional Retrieval-Augmented Generation (RAG) pipelines work well for simple queries—but when users ask complex, multi-part questions or refer to previous conversation history, they often fall short. That’s where Agentic Retrieval comes in: a game-changing advancement in Azure AI Search that brings LLM-powered reasoning directly into the retrieval layer.
This session unveils how agentic techniques elevate your RAG-based applications by introducing intelligent query planning, subquery decomposition, parallel execution, and result merging—all orchestrated by a new Knowledge Agent. You’ll learn how this approach significantly boosts relevance, groundedness, and answer quality, especially for sophisticated enterprise use cases.
Key takeaways:
- Understand the evolution from keyword and vector search to agentic query orchestration
- See how full conversation context improves retrieval accuracy
- Explore measurable improvements in answer relevance and completeness (up to 40% gains!)
- Get hands-on guidance on integrating Agentic Retrieval with Azure AI Foundry and SDKs
- Discover how to build scalable, AI-first applications powered by this new paradigm
Whether you're building intelligent copilots, enterprise Q&A bots, or AI-driven search solutions, this session will equip you with the tools and patterns to push beyond traditional RAG.
Key AI Technologies Used by Indian Artificial Intelligence CompaniesMypcot Infotech
Indian tech firms are rapidly adopting advanced tools like machine learning, natural language processing, and computer vision to drive innovation. These key AI technologies enable smarter automation, data analysis, and decision-making. Leading developments are shaping the future of digital transformation among top artificial intelligence companies in India.
For more information please visit here https://www.mypcot.com/artificial-intelligence
1. Unit 8
Classes and Objects; Inheritance
Special thanks to Roy McElmurry, John Kurkowski, Scott Shawcroft, Ryan Tucker, Paul Beck for their work.
Except where otherwise noted, this work is licensed under:
http://creativecommons.org/licenses/by-nc-sa/3.0
2. 2
OOP, Defining a Class
• Python was built as a procedural language
– OOP exists and works fine, but feels a bit more "tacked on"
– Java probably does classes better than Python (gasp)
• Declaring a class:
class name:
statements
3. 3
Fields
name = value
– Example:
class Point:
x = 0
y = 0
# main
p1 = Point()
p1.x = 2
p1.y = -5
– can be declared directly inside class (as shown here)
or in constructors (more common)
– Python does not really have encapsulation or private fields
• relies on caller to "be nice" and not mess with objects' contents
point.py
1
2
3
class Point:
x = 0
y = 0
4. 4
Using a Class
import class
– client programs must import the classes they use
point_main.py
1
2
3
4
5
6
7
8
9
10
from Point import *
# main
p1 = Point()
p1.x = 7
p1.y = -3
...
# Python objects are dynamic (can add fields any time!)
p1.name = "Tyler Durden"
5. 5
Object Methods
def name(self, parameter, ..., parameter):
statements
– self must be the first parameter to any object method
• represents the "implicit parameter" (this in Java)
– must access the object's fields through the self reference
class Point:
def translate(self, dx, dy):
self.x += dx
self.y += dy
...
6. 6
"Implicit" Parameter (self)
• Java: this, implicit
public void translate(int dx, int dy) {
x += dx; // this.x += dx;
y += dy; // this.y += dy;
}
• Python: self, explicit
def translate(self, dx, dy):
self.x += dx
self.y += dy
– Exercise: Write distance, set_location, and
distance_from_origin methods.
7. 7
Exercise Answer
point.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from math import *
class Point:
x = 0
y = 0
def set_location(self, x, y):
self.x = x
self.y = y
def distance_from_origin(self):
return sqrt(self.x * self.x + self.y * self.y)
def distance(self, other):
dx = self.x - other.x
dy = self.y - other.y
return sqrt(dx * dx + dy * dy)
8. 8
Calling Methods
• A client can call the methods of an object in two ways:
– (the value of self can be an implicit or explicit parameter)
1) object.method(parameters)
or
2) Class.method(object, parameters)
• Example:
p = Point(3, -4)
p.translate(1, 5)
Point.translate(p, 1, 5)
9. 9
Constructors
def __init__(self, parameter, ..., parameter):
statements
– a constructor is a special method with the name __init__
– Example:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
...
• How would we make it possible to construct a
Point() with no parameters to get (0, 0)?
10. 10
toString and __str__
def __str__(self):
return string
– equivalent to Java's toString (converts object to a string)
– invoked automatically when str or print is called
Exercise: Write a __str__ method for Point objects that
returns strings like "(3, -14)"
def __str__(self):
return "(" + str(self.x) + ", " + str(self.y) + ")"
11. 11
Complete Point Class
point.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from math import *
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def distance_from_origin(self):
return sqrt(self.x * self.x + self.y * self.y)
def distance(self, other):
dx = self.x - other.x
dy = self.y - other.y
return sqrt(dx * dx + dy * dy)
def translate(self, dx, dy):
self.x += dx
self.y += dy
def __str__(self):
return "(" + str(self.x) + ", " + str(self.y) + ")"
12. 12
Operator Overloading
• operator overloading: You can define functions so that
Python's built-in operators can be used with your class.
• See also: http://docs.python.org/ref/customization.html
Operator Class Method
- __neg__(self, other)
+ __pos__(self, other)
* __mul__(self, other)
/ __truediv__(self, other)
Unary Operators
- __neg__(self)
+ __pos__(self)
Operator Class Method
== __eq__(self, other)
!= __ne__(self, other)
< __lt__(self, other)
> __gt__(self, other)
<= __le__(self, other)
>= __ge__(self, other)
13. 13
Exercise
• Exercise: Write a Fraction class to represent rational
numbers like 1/2 and -3/8.
• Fractions should always be stored in reduced form; for
example, store 4/12 as 1/3 and 6/-9 as -2/3.
– Hint: A GCD (greatest common divisor) function may help.
• Define add and multiply methods that accept another
Fraction as a parameter and modify the existing
Fraction by adding/multiplying it by that parameter.
• Define +, *, ==, and < operators.
14. 14
Generating Exceptions
raise ExceptionType("message")
– useful when the client uses your object improperly
– types: ArithmeticError, AssertionError, IndexError,
NameError, SyntaxError, TypeError, ValueError
– Example:
class BankAccount:
...
def deposit(self, amount):
if amount < 0:
raise ValueError("negative amount")
...
15. 15
Inheritance
class name(superclass):
statements
– Example:
class Point3D(Point): # Point3D extends Point
z = 0
...
• Python also supports multiple inheritance
class name(superclass, ..., superclass):
statements
(if > 1 superclass has the same field/method, conflicts are resolved in left-to-right order)
16. 16
Calling Superclass Methods
• methods: class.method(object, parameters)
• constructors: class.__init__(parameters)
class Point3D(Point):
z = 0
def __init__(self, x, y, z):
Point.__init__(self, x, y)
self.z = z
def translate(self, dx, dy, dz):
Point.translate(self, dx, dy)
self.z += dz