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.
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.
The document discusses object-oriented programming concepts in Python like classes, objects, methods, variables, inheritance and polymorphism. It provides examples of how to define a class with attributes and methods, create objects, and access variables and call methods. It also explains different types of methods like instance methods, class methods, static methods and variable types like instance and static/class variables. Inheritance allows creating new classes from existing classes for code reusability.
The document introduces Python modules and importing. It discusses three formats for importing modules: import somefile, from somefile import *, and from somefile import className. It describes commonly used Python modules like sys, os, and math. It also covers defining your own modules, directories for module files, object-oriented programming in Python including defining classes, creating and deleting instances, methods and self, accessing attributes and methods, attributes, inheritance, and redefining methods.
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.
Here is a Python class with the specifications provided in the question:
class PICTURE:
def __init__(self, pno, category, location):
self.pno = pno
self.category = category
self.location = location
def FixLocation(self, new_location):
self.location = new_location
This defines a PICTURE class with three instance attributes - pno, category and location as specified in the question. It also defines a FixLocation method to assign a new location as required.
This document provides an overview of object-oriented programming (OOP) with Python. It defines some key OOP concepts like objects, classes, encapsulation, inheritance, and polymorphism. It explains that in OOP, data and functions that operate on that data are bundled together into objects. Classes provide templates for creating objects with common properties and functions. The document also gives examples of various OOP features like class variables, instance variables, methods, and constructors.
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.
Chap 3 Python Object Oriented Programming - Copy.pptmuneshwarbisen1
The document discusses object oriented programming concepts in Python including classes, objects, instances, methods, inheritance, and class attributes. It provides examples of defining classes, instantiating objects, using methods, and the difference between class and instance attributes. Key concepts covered include defining classes with the class keyword, creating object instances, using the __init__() method for initialization, and allowing derived classes to inherit from base classes.
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.
This document discusses object-oriented programming concepts in Python like classes, objects, encapsulation, inheritance and polymorphism. It explains that classes are user-defined blueprints that contain data fields and methods, and objects are instances of classes. The key concepts of OOP like data encapsulation, abstraction, inheritance and polymorphism are explained with examples in Python. Various special methods like __init__(), __str__(), __repr__() and their usage with classes are also covered.
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 provides an introduction to object oriented programming in Python. It discusses why OOP is useful, defines some key concepts like classes, objects, methods, and variables. It provides an example of modeling a Taxi using a Taxi class with attributes like driver name and methods like pickUpPassenger. It shows how to define a class, create objects from the class, and call methods on those objects. It also introduces the concept of class variables that are shared among all objects versus instance variables that are unique to each object.
در این جلسه به بررسی بحث برنامه نویسی شی گرا و کلاس ها در پایتون پرداختیم
PySec101 Fall 2013 J7E1 By Mohammad Reza Kamalifard
Talk About:
Object oriented programming and Classes in Python
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.
Object-oriented programming (OOP) organizes code around data objects rather than functions. In Python, classes are user-defined templates for objects that contain attributes (data) and methods (functions). When a class is instantiated, an object is created with its own copies of the attributes. Self refers to the object itself and allows methods to access and modify its attributes. Classes in Python allow for code reusability, modularity, and flexibility through encapsulation, inheritance, and polymorphism.
Python classes allow for the creation of object-oriented programming in Python. Classes define blueprints for objects with shared attributes and behaviors. Key aspects of classes include defining attributes and methods, constructing objects from classes, inheritance that allows subclasses to extend parent classes, and special methods that enable built-in behaviors. Classes are a fundamental part of Python that enable code reuse and organization.
Python classes allow for the creation of object-oriented programming through defining blueprints for objects with shared attributes and behaviors. Classes are created using the class keyword and contain attributes like variables and methods like functions. Objects are instantiated from classes and can access both class level and instance level attributes. Key concepts covered include inheritance, encapsulation, polymorphism, and special methods.
This document provides an overview of object-oriented programming (OOP) with Python. It defines some key OOP concepts like objects, classes, encapsulation, inheritance, and polymorphism. It explains that in OOP, data and functions that operate on that data are bundled together into objects. Classes provide templates for creating objects with common properties and functions. The document also gives examples of various OOP features like class variables, instance variables, methods, and constructors.
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.
Chap 3 Python Object Oriented Programming - Copy.pptmuneshwarbisen1
The document discusses object oriented programming concepts in Python including classes, objects, instances, methods, inheritance, and class attributes. It provides examples of defining classes, instantiating objects, using methods, and the difference between class and instance attributes. Key concepts covered include defining classes with the class keyword, creating object instances, using the __init__() method for initialization, and allowing derived classes to inherit from base classes.
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.
This document discusses object-oriented programming concepts in Python like classes, objects, encapsulation, inheritance and polymorphism. It explains that classes are user-defined blueprints that contain data fields and methods, and objects are instances of classes. The key concepts of OOP like data encapsulation, abstraction, inheritance and polymorphism are explained with examples in Python. Various special methods like __init__(), __str__(), __repr__() and their usage with classes are also covered.
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 provides an introduction to object oriented programming in Python. It discusses why OOP is useful, defines some key concepts like classes, objects, methods, and variables. It provides an example of modeling a Taxi using a Taxi class with attributes like driver name and methods like pickUpPassenger. It shows how to define a class, create objects from the class, and call methods on those objects. It also introduces the concept of class variables that are shared among all objects versus instance variables that are unique to each object.
در این جلسه به بررسی بحث برنامه نویسی شی گرا و کلاس ها در پایتون پرداختیم
PySec101 Fall 2013 J7E1 By Mohammad Reza Kamalifard
Talk About:
Object oriented programming and Classes in Python
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.
Object-oriented programming (OOP) organizes code around data objects rather than functions. In Python, classes are user-defined templates for objects that contain attributes (data) and methods (functions). When a class is instantiated, an object is created with its own copies of the attributes. Self refers to the object itself and allows methods to access and modify its attributes. Classes in Python allow for code reusability, modularity, and flexibility through encapsulation, inheritance, and polymorphism.
Python classes allow for the creation of object-oriented programming in Python. Classes define blueprints for objects with shared attributes and behaviors. Key aspects of classes include defining attributes and methods, constructing objects from classes, inheritance that allows subclasses to extend parent classes, and special methods that enable built-in behaviors. Classes are a fundamental part of Python that enable code reuse and organization.
Python classes allow for the creation of object-oriented programming through defining blueprints for objects with shared attributes and behaviors. Classes are created using the class keyword and contain attributes like variables and methods like functions. Objects are instantiated from classes and can access both class level and instance level attributes. Key concepts covered include inheritance, encapsulation, polymorphism, and special methods.
Creating Python Variables using Replit softwareafsheenfaiq2
This document provides resources for learning Python programming concepts related to math operators, variables, input/output, and integer conversion. It includes examples of Python code to perform basic math operations with fixed numbers and variables, convert strings to integers for calculations, get number input from the user, and modify variable values. The document ends with homework challenges to create programs calculating the area and perimeter of a rectangle, a restaurant tip calculator, and the volume and surface area of a cuboid.
Introduction to Declaring Functions in Pythonafsheenfaiq2
This document discusses functions in Python programming. It begins by outlining the objectives of understanding why programmers divide programs into functions and how to define and call functions in Python. It then provides an informal introduction to functions, explaining how they can reduce code duplication and increase modularity. The document goes on to describe key details about functions, including formal parameters, actual parameters, scope, and returning values. It also discusses how functions can modify parameters by making changes to the values passed into the function. Overall, the document serves as an introduction to defining, calling, and using functions in Python programs.
Sample Exam Questions on Python for revisionafsheenfaiq2
This document provides 30 sample exam questions for part 1 of the final exam for the course CPIT 110 (Problem Solving and Programming). The questions cover topics from chapters 1-6 related to functions, including defining and calling functions, parameters, return values, scope of variables, and default arguments. The questions are multiple choice with 4 possible answers each.
The document provides an overview of the content for Week 2 of an IOT course, which includes 4 sessions on embedded systems and IOT. Session 1 covers an introduction to embedded systems and their essential components, as well as the importance of programming languages. Session 2 further introduces IOT. Session 3 discusses what embedded systems are and how to draw and label their block diagrams. Session 4 recaps the lessons and includes an individual activity to assess understanding.
The document summarizes a lesson on exploring Arduino input and output pins. It discusses the three main types of Arduino pins - digital, analog, and power pins. Digital pins can be used for both input and output and represent either high or low signals. Analog pins read voltage values from sensors. The document provides examples of input devices like buttons, sensors and output devices like LEDs, motors, and buzzers that can be connected to an Arduino board. It describes using a button to control an LED blinking or music playing as example activities.
This document provides information about a lesson on using pen shade and stamp block tools in Scratch programming. The lesson objective is for students to create animations using the pen shade and stamp features of sprites. Success criteria include using the set pen shade and change pen shade blocks to create animations and using the stamp block. Key vocabulary defined includes shade, stamp, and descriptions of the pen shade and stamp blocks. The activity asks students to complete a pen shade task uploaded to Google Classroom.
This document outlines lessons for a week 4 AP Computer Science course. It discusses program development processes including incremental and iterative approaches. Students will learn to design programs and user interfaces, incorporating investigations to determine requirements. The importance of program documentation is emphasized to help with development, maintenance, and giving proper credit to original authors. Documentation should acknowledge any code from other sources and include comments within the code.
2D Polygons using Pen tools- Week 21.pptxafsheenfaiq2
This document outlines a lesson plan for students to learn how to create 2D geometric shape animations in Scratch using various pen tools. The lesson objectives are for students to design animations that draw shapes using pen color, size, and clear features of sprites. Key pen blocks and vocabulary are defined. Examples of circle, polygon, and complex shape drawings are provided. Students are assigned an activity to complete a pen task uploaded on Google Classroom.
Strings in Python are arrays of bytes representing Unicode characters. Individual characters are represented as strings of length 1. Strings are immutable, so their elements cannot be modified once created. However, strings can be sliced to access substrings.
Python has many built-in string methods for common string operations like capitalization, stripping whitespace, formatting, searching/replacing substrings and more. Methods like find(), count(), startswith() check for substrings within a string. Length, case changing, and padding methods modify strings. Character methods like ord() and chr() convert between characters and ASCII values.
This document provides instructions for a lesson on using the Size block in Scratch to create animations showing growing and shrinking effects. The lesson objective is for students to design and create an animation using the Size block to change a sprite's size. The success criteria are that students should be able to make a sprite grow and shrink in size and repeat the motion. Students are instructed to choose a backdrop and two sprites, then use the Size block to show a growing and shrinking effect and submit a screenshot.
This document provides an overview of using lists and dictionaries in Python. It discusses how to create, modify, and access elements in lists and dictionaries. Some key points covered include using list methods like append(), sort(), and remove() to manipulate list elements, creating nested lists to group related data, and using dictionaries to store and lookup data through key-value pairs. Shared references in lists are also explained, where modifying a list through one reference variable affects other variables referring to the same list.
This document discusses the string data type in Python. It explains that strings are sequences of characters that can be indexed, sliced, concatenated, and operated on using various string methods. Lists are also introduced as mutable sequences that can contain heterogeneous data types. Common string and list operations like indexing, slicing, length calculation, and concatenation are demonstrated through examples.
Gr 12 - Buzzer Project on Sound Production (W10).pptxafsheenfaiq2
This document provides instructions for a lesson on buzzer sensors for an Arduino project. It includes:
1) Objectives to define and explain the construction and working of active and passive buzzer sensors, and create a project using them.
2) A list of materials needed for the sound production project, including an Arduino UNO board, sensor shield, passive buzzer, and jumper wires.
3) Directions to connect the components, upload code to produce sounds with the passive buzzer, and compare it to an active buzzer.
This document discusses various network topologies including bus, ring, star, mesh, and hybrid topologies. It describes the basic characteristics of each topology such as their physical layout, advantages, and disadvantages. A bus topology uses a single backbone cable to connect all nodes without devices, while a ring topology connects each node to the two nearest in a circular formation. A star topology connects all nodes to a central hub or switch. A mesh topology fully connects all nodes to each other. Choosing a topology depends on factors like the network size, expected growth, and need for fault tolerance.
The document provides an overview of an Internet-of-Things course, including weekly topics, labs, and administrative items. The course covers fundamentals of IoT in the first week, then moves to topics like human-computer interfaces, computer networks, sensor networks, IoT cloud/analytics, and security. Labs involve programming sensors, networks, and IoT integration. Administrative items include assignments, exams, and weekly lab reports.
This document provides an overview of Python programming concepts for a summer engineering program. It covers setting up Python environments, basic syntax like indentation and variable types, arithmetic and logical operators, conditional statements like if/else and for/while loops, functions, error handling, file input/output, and two assignment tasks involving computing prices from stock and writing/reading to a file.
This document provides information about a Scratch programming course, including lesson plans, objectives, and instructions. It summarizes that students should maintain a notebook for the Scratch course with dates, topics, standards and objectives for each lesson. It also describes creating accounts on the Scratch website to work on projects and share them in the classroom. The first chapter covers differentiating between programs and programming, and using blocks like motion to make a sprite move on the screen.
Soulmaite review - Find Real AI soulmate reviewSoulmaite
Looking for an honest take on Soulmaite? This Soulmaite review covers everything you need to know—from features and pricing to how well it performs as a real AI soulmate. We share how users interact with adult chat features, AI girlfriend 18+ options, and nude AI chat experiences. Whether you're curious about AI roleplay porn or free AI NSFW chat with no sign-up, this review breaks it down clearly and informatively.
Discover 7 best practices for Salesforce Data Cloud to clean, integrate, secure, and scale data for smarter decisions and improved customer experiences.
Bridging the divide: A conversation on tariffs today in the book industry - T...BookNet Canada
A collaboration-focused conversation on the recently imposed US and Canadian tariffs where speakers shared insights into the current legislative landscape, ongoing advocacy efforts, and recommended next steps. This event was presented in partnership with the Book Industry Study Group.
Link to accompanying resource: https://bnctechforum.ca/sessions/bridging-the-divide-a-conversation-on-tariffs-today-in-the-book-industry/
Presented by BookNet Canada and the Book Industry Study Group on May 29, 2025 with support from the Department of Canadian Heritage.
Trends Artificial Intelligence - Mary MeekerClive Dickens
Mary Meeker’s 2024 AI report highlights a seismic shift in productivity, creativity, and business value driven by generative AI. She charts the rapid adoption of tools like ChatGPT and Midjourney, likening today’s moment to the dawn of the internet. The report emphasizes AI’s impact on knowledge work, software development, and personalized services—while also cautioning about data quality, ethical use, and the human-AI partnership. In short, Meeker sees AI as a transformative force accelerating innovation and redefining how we live and work.
In this talk, Elliott explores how developers can embrace AI not as a threat, but as a collaborative partner.
We’ll examine the shift from routine coding to creative leadership, highlighting the new developer superpowers of vision, integration, and innovation.
We'll touch on security, legacy code, and the future of democratized development.
Whether you're AI-curious or already a prompt engineering, this session will help you find your rhythm in the new dance of modern development.
Your startup on AWS - How to architect and maintain a Lean and Mean accountangelo60207
Prevent infrastructure costs from becoming a significant line item on your startup’s budget! Serial entrepreneur and software architect Angelo Mandato will share his experience with AWS Activate (startup credits from AWS) and knowledge on how to architect a lean and mean AWS account ideal for budget minded and bootstrapped startups. In this session you will learn how to manage a production ready AWS account capable of scaling as your startup grows for less than $100/month before credits. We will discuss AWS Budgets, Cost Explorer, architect priorities, and the importance of having flexible, optimized Infrastructure as Code. We will wrap everything up discussing opportunities where to save with AWS services such as S3, EC2, Load Balancers, Lambda Functions, RDS, and many others.
Developing Schemas with FME and Excel - Peak of Data & AI 2025Safe Software
When working with other team members who may not know the Esri GIS platform or may not be database professionals; discussing schema development or changes can be difficult. I have been using Excel to help illustrate and discuss schema design/changes during meetings and it has proven a useful tool to help illustrate how a schema will be built. With just a few extra columns, that Excel file can be sent to FME to create new feature classes/tables. This presentation will go thru the steps needed to accomplish this task and provide some lessons learned and tips/tricks that I use to speed the process.
What is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to KnowSMACT Works
In today's fast-paced business landscape, financial planning and performance management demand powerful tools that deliver accurate insights. Oracle EPM (Enterprise Performance Management) stands as a leading solution for organizations seeking to transform their financial processes. This comprehensive guide explores what Oracle EPM is, its key benefits, and how partnering with the right Oracle EPM consulting team can maximize your investment.
Data Virtualization: Bringing the Power of FME to Any ApplicationSafe Software
Imagine building web applications or dashboards on top of all your systems. With FME’s new Data Virtualization feature, you can deliver the full CRUD (create, read, update, and delete) capabilities on top of all your data that exploit the full power of FME’s all data, any AI capabilities. Data Virtualization enables you to build OpenAPI compliant API endpoints using FME Form’s no-code development platform.
In this webinar, you’ll see how easy it is to turn complex data into real-time, usable REST API based services. We’ll walk through a real example of building a map-based app using FME’s Data Virtualization, and show you how to get started in your own environment – no dev team required.
What you’ll take away:
-How to build live applications and dashboards with federated data
-Ways to control what’s exposed: filter, transform, and secure responses
-How to scale access with caching, asynchronous web call support, with API endpoint level security.
-Where this fits in your stack: from web apps, to AI, to automation
Whether you’re building internal tools, public portals, or powering automation – this webinar is your starting point to real-time data delivery.
Domino IQ – What to Expect, First Steps and Use Casespanagenda
Webinar Recording: https://www.panagenda.com/webinars/domino-iq-what-to-expect-first-steps-and-use-cases/
HCL Domino iQ Server – From Ideas Portal to implemented Feature. Discover what it is, what it isn’t, and explore the opportunities and challenges it presents.
Key Takeaways
- What are Large Language Models (LLMs) and how do they relate to Domino iQ
- Essential prerequisites for deploying Domino iQ Server
- Step-by-step instructions on setting up your Domino iQ Server
- Share and discuss thoughts and ideas to maximize the potential of Domino iQ
DevOps in the Modern Era - Thoughtfully Critical PodcastChris Wahl
https://youtu.be/735hP_01WV0
My journey through the world of DevOps! From the early days of breaking down silos between developers and operations to the current complexities of cloud-native environments. I'll talk about my personal experiences, the challenges we faced, and how the role of a DevOps engineer has evolved.
Down the Rabbit Hole – Solving 5 Training RoadblocksRustici Software
Feeling stuck in the Matrix of your training technologies? You’re not alone. Managing your training catalog, wrangling LMSs and delivering content across different tools and audiences can feel like dodging digital bullets. At some point, you hit a fork in the road: Keep patching things up as issues pop up… or follow the rabbit hole to the root of the problems.
Good news, we’ve already been down that rabbit hole. Peter Overton and Cameron Gray of Rustici Software are here to share what we found. In this webinar, we’ll break down 5 training roadblocks in delivery and management and show you how they’re easier to fix than you might think.
Jeremy Millul - A Talented Software DeveloperJeremy Millul
Jeremy Millul is a talented software developer based in NYC, known for leading impactful projects such as a Community Engagement Platform and a Hiking Trail Finder. Using React, MongoDB, and geolocation tools, Jeremy delivers intuitive applications that foster engagement and usability. A graduate of NYU’s Computer Science program, he brings creativity and technical expertise to every project, ensuring seamless user experiences and meaningful results in software development.
2. Lecture 3 outline
• Python class and object
• Class implementation with Python
• Add attributes and methods
• Initialisation of objects
• Class vs instance variables
• Class vs instance vs static methods
• Public, protected and private variables and methods
• A case study
2
4. Class definition
To define a class you need to:
1. Use the class keyword (spelled with all lowercase letters)
2. Specify its name. A class name is its identifier.
By convention, class names
- can include only letters, digits, and underscores. No spaces.
- begin with a capital letter. If several words are combined, each shall start with a capital letter too
- should be meaningful DpGh, Abc, R1,WelcomeToPython, StaffMember, StreamBuffer
3. The class definition line is followed by the class contents, indented. pass can
be
used for skipping the class body.
4. Python uses a four-space indentation to delimit the classes, rather than
brackets
class HelloWorld:
pass
Class body
Class declaration
5. Class definition
• Although our first class does nothing, we still can run the program.
1. Save the class definition in a file named HelloWorld.py
2. Implement and run the program in IDLE.
6. Adding arbitrary attributes
• Objects should contain data which are defined as the attribute
• We can set arbitrary attributes on an instantiated object using ‘.’ (dot
notation).
• Syntax: <object>.<attribute> = <value>
7. Adding object behaviors
• We have data, and it is time to add behaviors.
• We start with a method called ‘greet’ which prints “Hello object world”.
• ‘greet’ method does not require any parameters.
• We call the method through the dot notation: <object>.<method>
8. Adding behaviors
• In Python, a method is defined with the def keyword, followed by a space,
the name of the method, and a set of parentheses containing the
parameter list.
• Method definition is terminated with a colon (:)
• The method body starts from the next line and is indented.
Syntax:
<def><methodName><(parameter list):>
<four space indentation><method body>
9. ‘self’
argument
• With the same class definition, we can create different objects.
Therefore, we need to know which object calls the methods (object
methods).
• Object methods shall contain an argument referring to the object
itself.
• Normally, this argument is named ‘self’. The ‘self’ argument is a
reference to the object that the method is being invoked on.
• Of course, you can also call it by another name, such as ‘this’ or ‘bob’.
But we never seen a real Python programmer use any other name for
this variable
• A normal function or a class method does not have this ‘self’
argument.
10. ‘self’
argument
• In Python OOP, a method is a function attached to a class.
• The ‘self’ parameter is a specific instance of that class.
• If you call the method with two different instances (objects), you are
calling the same method twice but passing two different objects as
the ‘self’ parameter
• When we call <object>.<method>, we do not have to pass the ‘self’
argument into it. It is because Python automatically pass it, i.e.,
method(object)
• Alternatively, we can invoke the function by the class name, and
explicitly pass our object as the ‘self’ argument using
<class>.<method(object)>
12. More arguments
• A method can contain multiple arguments
• Use the dot notation to call the method with all argument values (still
no need to include the ‘self’ argument) inside the parentheses
13. Adding attributes in your class definition
What if we forget to call the reset() function?
14. Summary
• Python is an interpreted language. The interpreter only ‘knows’ the code has been
executed.
• The ‘self’ argument is a reference to the object self. We should use ‘self.’ notation to access
the object functions and attribute values.
• If we try to access an attribute without a value, we will receive an error. Therefore, we must
make sure the attribute has a value before we use it.
• The ’reset()’ and ‘move()’ methods in the previous example assign values to attributes
‘self.x’ and ‘self.y’, and one of them must be executed for both point objects before we
calculate the distance of the two point objects.
• However, how do users know that? Furthermore, how do we force users to call the
‘reset()’
method?
• The better way is to let the interpreter call ‘reset()’ automatically for every new object
created.
• In OOD, a constructor (i.e., the function with the class name) refers to a special method that
creates and initialises the object automatically when it is created
• The Python initialisation method is the same as any other method but with a special name,
init (the leading and trailing are double underscores)
16. Explain your class
• It is important to write API documentation to summarize what each object and
method does
• The best way to do it is to write it right into your code through the docstrings
• Docstrings are simply Python strings enclosed with apostrophes (') or quotation
marks (") characters.
• If docstrings are quite long and span multiple lines (the style guide suggests that
the line length should not exceed 80 characters), it can be formatted as multi-line
strings, enclosed in matching triple apostrophe (''') or triple quote (""") characters.
• A docstring should clearly and concisely summarize the purpose of the class or
method it is describing.
• It should explain any parameters whose usage is not immediately obvious and is
also a good place to include short examples of how to use the API.
• Any caveats or problems an unsuspecting user of the API should be aware of
should also be noted.
18. Object (instance) vs class (static) variables
• Object variables are for data unique to
each object.
• Object variables are defined inside
methods with the prefix ‘self’
• Access via self.<InstanceVariable>
• Class variables are for data shared by all
objects of the same class.
• Class variables are defined outside
methods
• Access via cls.<ClassVariable> or
<ClassName>.<ClassVariable>
19. Instance (object) vs class (static) variables
• start_point_x and start_point_y are class variables
• Changing the class variable values with Object point1,
then we can see the class variable values are modified
with Object point2
• Object point1 changes the start point from (0, 0) to
(1, 1). However, Object point2 is not initialised by the
new start point (1,1). Can you guess why?
• Can we use Point.start_point_x and
Point_start_point_y in the init() method?
20. Instance (object) vs class (static) variables
• No, we can not. It is because the class variables are not
created yet when we call the init() method
• How to resolve this problem?
• We use a sentinel default value instead.
21. Sentinel Default Value
• Can you understand and explain how the code is
executed and what the results are?
• Try to ‘run’ the code in your mind and write
down all outputs.
22. Class method
• Problem: we still have to create a Point object first, and then we can
modify the class variable start_point_x and start_point_y.
• Question: can we modify the start point directly without creating a Point
object?
• Answer: yes, we can. We can define a ‘change_start_point()’ method as
a class method by marking this method with a ‘@classmethod’
decorator.
• Then we can call the method with the class name, i.e.,
<ClassName>.<ClassMethod>.
• Actually, you can also call the class method with an object of the class,
such as <objectName>.<ClassMethod>. They do the same job.
23. Class method vs object method
• The object method has access to the object via the
’self’ argument. When the method is called, Python
replaces the ’self’ argument with the real object
name.
• Calling class method doesn’t have access to the
object, but only to the class. Python automatically
passes the class name as the first argument to the
function when we call the class method.
• Summary: Python calls the object method by
passing the object name as the first argument, and
calls the class method by passing the class name as
the first argument
24. Static method
• Question: Java has the static method, does Python also have the
static method?
• Answer: Yes, Python also has the static method, but the
definition of
‘static’ in Python is very different from Java or other OOPs.
• Java’s static method is the same as Python’s class method
• Python’s static method is the same as Python’s normal method,
i.e.,
no object instance or class will be pasted as the first argument.
• Python’s static method can be defined by marking this method with a
‘@staticmethod’ decorator.
• You are allowed to call a static method via either
26. Python access control
Most OOP languages have a concept of access control.
• (+) public members are accessible from outside the class.
• (-) private members are accessible from inside the class only.
• (#) protected members are accessible from inside the class or sub-classes
However, Python does not follow this exactly.
• Python does not believe in enforcing laws that might someday get in your way.
• Technically, all class members (attributes and methods) are publicly available, i.e., they can be
accessed directly from external.
• In Python, prefixes are used to only interpret the access control of members.
• _ (single underscore) prefixed to a member makes it protected but still can be accessed directly.
• (double underscore) prefixed to a member makes it private. It gives a strong suggestion not to
touch it from outside the class. Any attempt to do so will result in an AttributeError.
• However, Python performs name mangling of private variables. Every private member with a
double underscore can be accessed by adding the prefix ‘_<ClassName>’. So, private members can
still be accessed from outside the class, but the practice should be refrained.
28. Python execution control
• A program written in C or Java needs the main() function to indicate the
starting point of execution.
• Python does not need the main() function as it is an interpreter-based
language.
• The execution of the Python program file starts from the first
statement.
• Python uses a special variable called ‘ name ’ (string) to
maintain the
scope of the code being executed.
• The top-level scope (top-level code executes here) is referred by the
value
‘ main ’
• You can check the scope in Python shell by typing ‘ name ’ in
IDEL.
29. Python execution control
• When you execute functions and
modules in the interpreter
shell directly,
they will be executed in the top-
level scope ‘ main ’
• We can also save a Python
program as a Python file, which
may contain multiple functions
and statements, such as
30. Python execution control
• We can use the command prompt/terminal to execute the Python file as a script. Then
the scope is ‘ main ’.
• We can also use the Python file as a module in another file or in interactive shell by
importing it. Then the scope is the module’s name, but not the ‘ main ’.
31. Python execution control
• The import statement starts
executing from the first statement
till the last statement.
• What if we just want to use the
‘add()’ method but not print the
details?
• We can use the special variable
‘ name ’ to check the scope
and execute the other statements
only when it executes from the
command prompt/terminal with
the scope of ‘ main ’ but not
when importing.
32. Python execution control
• However, when we execute it
from the command
prompt/terminal, it still executes
all statements because of it
being executed in the top-level
scope
‘ main ’.
• Thus, value of the ‘ name ’
allows the Python interpreter to
determine whether a module is
intended to be an executable
script.
33. A case study
Design and implement a Python program with OOD & OOP to calculate the
length of a given line segment.
Step 1: OOA
• To calculate the length of a given line segment, a LineSegment class can be
defined. The LineSegment class should contain two points, i.e., the starting
point and the ending point. The length of a line segment is the Cartesian
distance between the two points. So we also need to define a Point class.
• So the LineSegment class should have two points (attribute) and can
calculate the Cartesian distance of two points (behavior)
• To represent a point, a Point class should contain the coordinate (x, y) as its
attributes.
34. A case study
Design and implement a Python program with OOD & OOP to calculate the
length of a given line segment.
Step 2: OOD (UML)
𝑑𝑖𝑠𝑡𝑎𝑛𝑐𝑒 = (𝑥1 − 𝑥2)2+(𝑦1
− 𝑦2)2
35. A case study
Design and implement a Python program with
OOD & OOP to calculate the length of a given
line segment.
Step 3: OOP (Python): complete the Python
class code and test code. Remember, you should
create the ‘ init ’ method for every class.
Step 4 Execution Control: use the ‘ name ’
variable to ensure your testing code is only
executed in the command prompt/terminal.
A further question: can you modify this design
and code to calculate the total length of
consecutive line segments, such as
(0,0)->(3,4)->(5,7)->(2,8)?