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 discusses classes and objects in Python. It defines a Point class to represent points in 2D space and a Rectangle class that uses a Point object for its corner attribute. Methods like find_center and grow_rectangle are defined that take objects as arguments and return or modify objects. Deep copying objects is discussed as an alternative to aliasing that allows modifying objects without changing the original. Pure functions that return new objects without modifying parameters are introduced.
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.
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.
Python Programming - VI. Classes and ObjectsRanel Padon
This document discusses classes and objects in Python programming. It covers key concepts like class attributes, instantiating classes to create objects, using constructors and destructors, composition where objects have other objects as attributes, and referencing objects. The document uses examples like a Time class to demonstrate class syntax and how to define attributes and behaviors for classes.
The document discusses Python objects and types. It covers key concepts like object-oriented programming in Python, classes and instances, namespaces, scoping, and exception handling. Some main points include:
- Everything in Python is an object with an identity, type, and value. Objects live in dynamic namespaces and can be accessed via names.
- Classes are type objects that act as templates for creating instances when called. Instances are objects with the same methods and attributes as its class.
- Namespaces are where names are mapped to objects. Python has module, class, and instance namespaces that follow LEGB scoping rules.
- Exceptions are class objects that inherit from the built-in Exception class. The raise statement is used
The document discusses Python programming concepts including lists, dictionaries, tuples, regular expressions, classes, objects, and methods. Key points:
- Lists are mutable sequences that can contain elements of any type. Dictionaries store elements as key-value pairs. Tuples are immutable sequences.
- Classes create user-defined data types by binding data (attributes) and functionality (methods). Objects are instances of classes that consume memory at runtime.
- Common methods include __init__() for initializing attributes and __str__() for string representation of objects. Computation is expressed through operations on objects, often representing real-world things.
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.
1) Python uses object-oriented programming concepts like objects and types, but OOP is not required to create Python applications. All Python objects have an identity, type and value.
2) Standard types in Python include numbers, strings, lists, tuples and dictionaries. Numbers have four sub-types and strings, lists and tuples allow sequential access of elements.
3) Python objects can be compared by value using comparison operators or by identity to determine if two objects are the same. Standard functions like type(), repr() and str() can also be applied to objects.
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.
Object oriented programming (OOP) in Python uses classes and objects. A class defines attributes and behaviors that objects can have. An object is an instance of a class that represents a real-world entity with unique attribute values and behaviors. The __init__() method initializes new objects by assigning values to attributes. Classes allow for code reuse through inheritance, where child classes inherit attributes and behaviors from parent classes.
This document discusses objects and graphics in Python programming. It covers:
- The concept of objects and how they combine data and operations to simplify programs.
- Various graphical objects available in the graphics library like points, circles, rectangles, etc.
- How to create object instances using constructors and call methods to perform graphical computations.
- Fundamental concepts of computer graphics like coordinate systems and transformations.
- Handling both mouse and text-based input in graphical programs.
- Writing simple interactive graphics programs using the graphics library.
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.
Python Training in Pune - Ethans Tech Pune Ethan's Tech
This document contains slides from a Python training module on core objects and built-in functions. It discusses various Python data types like numbers, strings, lists, tuples, dictionaries, sets, Boolean, and None. It covers operations and functions related to these objects. The slides provide examples and explanations of concepts like slicing, formatting, and membership operators. Quizzes are included to test understanding of string indexing and output of programs. An interesting fact about Raspberry Pi and its use in DIY projects is also mentioned.
This chapter discusses objects and graphics in Python programming. It introduces object-oriented programming concepts like classes, objects, and methods. The chapter covers creating graphical objects like points, circles, rectangles, and using a graphics library. It explains how to draw geometric shapes and text in a graphics window. Methods are used to manipulate graphical objects and change their properties.
Object.__class__.__dict__ - python object model and friends - with examplesRobert Lujo
Python object model - advanced and some not so advanced features, lot of code examples:
building blocks, objects, classes, functions, mutable and immutable, everything is an object, variables, global context, "executing" the module, standard types inheritance, multiple inheritance, mixins and mro, dynamic classes, metaclasses, property function and descriptors context managers & with, useful __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.
The document discusses Python programming concepts including lists, dictionaries, tuples, regular expressions, classes, objects, and methods. Key points:
- Lists are mutable sequences that can contain elements of any type. Dictionaries store elements as key-value pairs. Tuples are immutable sequences.
- Classes create user-defined data types by binding data (attributes) and functionality (methods). Objects are instances of classes that consume memory at runtime.
- Common methods include __init__() for initializing attributes and __str__() for string representation of objects. Computation is expressed through operations on objects, often representing real-world things.
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.
1) Python uses object-oriented programming concepts like objects and types, but OOP is not required to create Python applications. All Python objects have an identity, type and value.
2) Standard types in Python include numbers, strings, lists, tuples and dictionaries. Numbers have four sub-types and strings, lists and tuples allow sequential access of elements.
3) Python objects can be compared by value using comparison operators or by identity to determine if two objects are the same. Standard functions like type(), repr() and str() can also be applied to objects.
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.
Object oriented programming (OOP) in Python uses classes and objects. A class defines attributes and behaviors that objects can have. An object is an instance of a class that represents a real-world entity with unique attribute values and behaviors. The __init__() method initializes new objects by assigning values to attributes. Classes allow for code reuse through inheritance, where child classes inherit attributes and behaviors from parent classes.
This document discusses objects and graphics in Python programming. It covers:
- The concept of objects and how they combine data and operations to simplify programs.
- Various graphical objects available in the graphics library like points, circles, rectangles, etc.
- How to create object instances using constructors and call methods to perform graphical computations.
- Fundamental concepts of computer graphics like coordinate systems and transformations.
- Handling both mouse and text-based input in graphical programs.
- Writing simple interactive graphics programs using the graphics library.
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.
Python Training in Pune - Ethans Tech Pune Ethan's Tech
This document contains slides from a Python training module on core objects and built-in functions. It discusses various Python data types like numbers, strings, lists, tuples, dictionaries, sets, Boolean, and None. It covers operations and functions related to these objects. The slides provide examples and explanations of concepts like slicing, formatting, and membership operators. Quizzes are included to test understanding of string indexing and output of programs. An interesting fact about Raspberry Pi and its use in DIY projects is also mentioned.
This chapter discusses objects and graphics in Python programming. It introduces object-oriented programming concepts like classes, objects, and methods. The chapter covers creating graphical objects like points, circles, rectangles, and using a graphics library. It explains how to draw geometric shapes and text in a graphics window. Methods are used to manipulate graphical objects and change their properties.
Object.__class__.__dict__ - python object model and friends - with examplesRobert Lujo
Python object model - advanced and some not so advanced features, lot of code examples:
building blocks, objects, classes, functions, mutable and immutable, everything is an object, variables, global context, "executing" the module, standard types inheritance, multiple inheritance, mixins and mro, dynamic classes, metaclasses, property function and descriptors context managers & with, useful __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.
Wondershare PDFelement Pro 11.4.20.3548 Crack Free DownloadPuppy jhon
➡ 🌍📱👉COPY & PASTE LINK👉👉👉 ➤ ➤➤ https://drfiles.net/
Wondershare PDFelement Professional is professional software that can edit PDF files. This digital tool can manipulate elements in PDF documents.
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.
A brief introduction to OpenTelemetry, with a practical example of auto-instrumenting a Java web application with the Grafana stack (Loki, Grafana, Tempo, and Mimir).
Revolutionize Your Insurance Workflow with Claims Management SoftwareInsurance Tech Services
Claims management software enhances efficiency, accuracy, and satisfaction by automating processes, reducing errors, and speeding up transparent claims handling—building trust and cutting costs. Explore More - https://www.damcogroup.com/insurance/claims-management-software
Who will create the languages of the future?Jordi Cabot
Will future languages be created by language engineers?
Can you "vibe" a DSL?
In this talk, we will explore the changing landscape of language engineering and discuss how Artificial Intelligence and low-code/no-code techniques can play a role in this future by helping in the definition, use, execution, and testing of new languages. Even empowering non-tech users to create their own language infrastructure. Maybe without them even realizing.
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps CyclesMarjukka Niinioja
Teams delivering API are challenges with:
- Connecting APIs to business strategy
- Measuring API success (audit & lifecycle metrics)
- Partner/Ecosystem onboarding
- Consistent documentation, security, and publishing
🧠 The big takeaway?
Many teams can build APIs. But few connect them to value, visibility, and long-term improvement.
That’s why the APIOps Cycles method helps teams:
📍 Start where the pain is (one “metro station” at a time)
📈 Scale success across strategy, platform, and operations
🛠 Use collaborative canvases to get buy-in and visibility
Want to try it and learn more?
- Follow APIOps Cycles in LinkedIn
- Visit the www.apiopscycles.com site
- Subscribe to email list
-
14 Years of Developing nCine - An Open Source 2D Game FrameworkAngelo Theodorou
A 14-year journey developing nCine, an open-source 2D game framework.
This talk covers its origins, the challenges of staying motivated over the long term, and the hurdles of open-sourcing a personal project while working in the game industry.
Along the way, it’s packed with juicy technical pills to whet the appetite of the most curious developers.
Automating Map Production With FME and PythonSafe Software
People still love a good paper map, but every time a request lands on a GIS team’s desk, it takes time to create that perfect, individual map—even when you're ready and have projects prepped. Then come the inevitable changes and iterations that add even more time to the process. This presentation explores a solution for automating map production using FME and Python. FME handles the setup of variables, leveraging GIS reference layers and parameters to manage details like map orientation, label sizes, and layout elements. Python takes over to export PDF maps for each location and template size, uploading them monthly to ArcGIS Online. The result? Fresh, regularly updated maps, ready for anyone to grab anytime—saving you time, effort, and endless revisions while keeping users happy with up-to-date, accessible maps.
In a tight labor market and tighter economy, PMOs and resource managers must ensure that every team member is focused on the highest-value work. This session explores how AI reshapes resource planning and empowers organizations to forecast capacity, prevent burnout, and balance workloads more effectively, even with shrinking teams.
Join the Denver Marketo User Group, Captello and Integrate as we dive into the best practices, tools, and strategies for maintaining robust, high-performing databases. From managing vendors and automating orchestrations to enriching data for better insights, this session will unpack the key elements that keep your data ecosystem running smoothly—and smartly.
We will hear from Steve Armenti, Twelfth, and Aaron Karpaty, Captello, and Frannie Danzinger, Integrate.
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/
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentricNatan Silnitsky
At Wix, we revolutionized our platform by making integration events the backbone of our 4,000-microservice ecosystem. By abandoning traditional domain events for standardized Protobuf events through Kafka, we created a universal language powering our entire architecture.
We'll share how our "single-aggregate services" approach—where every CUD operation triggers semantic events—transformed scalability and extensibility, driving efficient event choreography, data lake ingestion, and search indexing.
We'll address our challenges: balancing consistency with modularity, managing event overhead, and solving consumer lag issues. Learn how event-based data prefetches dramatically improved performance while preserving the decoupling that makes our platform infinitely extensible.
Key Takeaways:
- How integration events enabled unprecedented scale and extensibility
- Practical strategies for event-based data prefetching that supercharge performance
- Solutions to common event-driven architecture challenges
- When to break conventional architectural rules for specific contexts
Maximizing Business Value with AWS Consulting Services.pdfElena Mia
An overview of how AWS consulting services empower organizations to optimize cloud adoption, enhance security, and drive innovation. Read More: https://www.damcogroup.com/aws-cloud-services/aws-consulting.
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.
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...Alluxio, Inc.
Alluxio Webinar
June 10, 2025
For more Alluxio Events: https://www.alluxio.io/events/
Speaker:
David Zhu (Engineering Manager @ Alluxio)
Storing data as Parquet files on cloud object storage, such as AWS S3, has become prevalent not only for large-scale data lakes but also as lightweight feature stores for training and inference, or as document stores for Retrieval-Augmented Generation (RAG). However, querying petabyte-to-exabyte-scale data lakes directly from S3 remains notoriously slow, with latencies typically ranging from hundreds of milliseconds to several seconds.
In this webinar, David Zhu, Software Engineering Manager at Alluxio, will present the results of a joint collaboration between Alluxio and a leading SaaS and data infrastructure enterprise that explored leveraging Alluxio as a high-performance caching and acceleration layer atop AWS S3 for ultra-fast querying of Parquet files at PB scale.
David will share:
- How Alluxio delivers sub-millisecond Time-to-First-Byte (TTFB) for Parquet queries, comparable to S3 Express One Zone, without requiring specialized hardware, data format changes, or data migration from your existing data lake.
- The architecture that enables Alluxio’s throughput to scale linearly with cluster size, achieving one million queries per second on a modest 50-node deployment, surpassing S3 Express single-account throughput by 50x without latency degradation.
- Specifics on how Alluxio offloads partial Parquet read operations and reduces overhead, enabling direct, ultra-low-latency point queries in hundreds of microseconds and achieving a 1,000x performance gain over traditional S3 querying methods.
Providing Better Biodiversity Through Better DataSafe Software
This session explores how FME is transforming data workflows at Ireland’s National Biodiversity Data Centre (NBDC) by eliminating manual data manipulation, incorporating machine learning, and enhancing overall efficiency. Attendees will gain insight into how NBDC is using FME to document and understand internal processes, make decision-making fully transparent, and shine a light on underlying code to improve clarity and reduce silent failures.
The presentation will also outline NBDC’s future plans for FME, including empowering staff to access and query data independently, without relying on external consultants. It will also showcase ambitions to connect to new data sources, unlock the full potential of its valuable datasets, create living atlases, and place its valuable data directly into the hands of decision-makers across Ireland—ensuring that biodiversity is not only protected but actively enhanced.
2. Announcements for Today
Assignment 1
• We have finished grading
• Resubmit until correct
§ Read feedback in CMS
§ Reupload/request regrade
• If you were very wrong…
§ You received an e-mail
§ More 1-on-1s this week
• Finish Survey 1
Assignment 2
• Posted last Friday
§ Written assignment
§ Do while revising A1
§ Relatively short (2-3 hrs)
• Due Thursday
§ Submit as a PDF
§ Scan or phone picture
§ US Letter format!
9/20/22 Objects 2
3. The Basic Python Types
• Type int:
§ Values: integers
§ Ops: +, –, *, //, %, **
• Type float:
§ Values: real numbers
§ Ops: +, –, *, /, **
• Type bool:
§ Values: True and False
§ Ops: not, and, or
• Type str:
§ Values: string literals
• Double quotes: "abc"
• Single quotes: 'abc'
§ Ops: + (concatenation)
9/20/22 Objects 3
Are the the only
types that exist?
4. Example: Points in 3D Space
def distance(x0,y0,z0,x1,y1,z1):
"""Returns distance between points (x0,y0,y1) and (x1,y1,z1)
Param x0: x-coord of 1st point
Precond: x0 is a float
Param y0: y-coord of 1st point
Precond: y0 is a float
Param z0: z-coord of 1st point
Precond: z0 is a float
….
"""
• This is very unwieldy
§ Specification is too long
§ Calls needs many params
§ Typo bugs are very likely
• Want to reduce params
§ Package points together
§ How can we do this?
9/20/22 Objects 4
5. Points as Their Own Type
def distance(p0,p1):
"""Returns distance between points p0 and p1
Param p0: The second point
Precond: p0 is a Point3
Param p1: The second point
Precond: p1 is a Point3"""
…
This lecture will help you
make sense of this spec.
9/20/22 Objects 5
6. Classes: Custom Types
• Class: Custom type not built into Python
§ Just like with functions: built-in & defined
§ Types not built-in are provided by modules
• Might seem weird: type(1) => <class 'int’>
§ In Python 3 type and class are synonyms
§ We will use the historical term for clarity
introcs provides several classes
9/20/22 Objects 6
7. Objects: Values for a Class
• Object: A specific value for a class type
§ Remember, a type is a set of values
§ Class could have infinitely many objects
• Example: Class is Point3
§ One object is origin; another x-axis (1,0,0)
§ These objects go in params distance function
• Sometimes refer to objects as instances
§ Because a value is an instance of a class
§ Creating an object is called instantiation
9/20/22 Objects 7
8. How to Instantiate an Object?
• Other types have literals
§ Example: 1, 'abc’, True
§ No such thing for objects
• Classes are provided by modules
§ Modules typically provide new functions
§ In this case, gives a function to make objects
• Constructor function has same name as class
§ Similar to types and type conversion
§ Example: str is a type, str(1) is a function call
9/20/22 Objects 8
9. Demonstrating Object Instantiation
>>> from introcs import Point3 # Module with class
>>> p = Point3(0,0,0) # Create point at origin
>>> p # Look at this new point
<class 'introcs.geom.point.Point3'>(0.0,0.0,0.0)
>>> type(p) == Point3 # Check the type
True
>>> q = Point3(1,2,3) # Make new point
>>> q # Look at this new point
<class 'introcs.geom.point.Point3'>(1.0,2.0,3.0)
9/20/22 Objects 9
10. What Does an Object Look Like?
• Objects can be a bit strange to understand
§ Don’t look as simple as strings or numbers
§ Example: <class 'introcs.Point3'>(0.0,0.0,0.0)
• To understand objects, need to visualize them
§ Use of metaphors to help us think like Python
§ Call frames (assume seen) are an example
• To visualize we rely on the Python Tutor
§ Website linked to from the course page
§ But use only that one! Other tutors are different.
9/20/22 Objects 10
11. Metaphor: Objects are Folders
>>> import introcs
>>> p = introcs.Point3(0,0,0)
>>> id(p)
id2
p
id2
x 0.0
y 0.0
z 0.0
Point3
Need to import module
that has Point class.
Constructor is function.
Prefix w/ module name.
Unique tab
identifier
9/20/22 Objects 11
Shows the ID of p.
12. Metaphor: Objects are Folders
id2
p
id2
x 0.0
y 0.0
z 0.0
Point3
• Idea: Data too “big” for p
§ Split into many variables
§ Put the variables in folder
§ They are called attributes
• Folder has an identifier
§ Unique (like a netid)
§ Cannot ever change
§ Has no real meaning;
only identifies folder
Unique tab
identifier
Attribute
9/20/22 Objects 12
13. Object Variables
• Variable stores object name
§ Reference to the object
§ Reason for folder analogy
• Assignment uses object name
§ Example: q = p
§ Takes name from p
§ Puts the name in q
§ Does not make new folder!
• This is the cause of many
mistakes for beginners
id2
p
id2
x 0.0
y 0.0
z 0.0
Point3
id2
q
9/20/22 Objects 13
14. Objects and Attributes
• Attributes live inside objects
§ Can access these attributes
§ Can use them in expressions
• Access: <variable>.<attr>
§ Look like module variables
§ Recall: math.pi
• Example
>>> p = introcs.Point3(1,2,3)
>>> a = p.x + p.y
id3
x 1.0
y 2.0
z 3.0
id3
p
Point3
9/20/22 Objects 14
15. Objects and Attributes
• Attributes live inside objects
§ Can access these attributes
§ Can use them in expressions
• Access: <variable>.<attr>
§ Look like module variables
§ Recall: math.pi
• Example
>>> p = introcs.Point3(1,2,3)
>>> a = p.x + p.y
id3
x 1.0
y 2.0
z 3.0
id3
p
Point3
3.0
a
9/20/22 Objects 15
16. Objects and Attributes
• Can also assign attributes
§ Reach into folder & change
§ Do without changing p
• <var>.<attr> = <exp>
§ Example: p.x = p.y+p.z
§ See this in visualizer
• This is very powerful
§ Another reason for objects
§ Why need visualization
id3
x 1.0
y 2.0
z 3.0
id3
p
Point3
5.0
x
9/20/22 Objects 16
17. Exercise: Attribute Assignment
• Recall, q gets name in p
>>> p = introcs.Point3(0,0,0)
>>> q = p
• Execute the assignments:
>>> p.x = 5.6
>>> q.x = 7.4
• What is value of p.x?
9/20/22 Objects 17
id4
p id4
q
A: 5.6
B: 7.4
C: id4
D: I don’t know
id4
x 0.0
y 0.0
z 0.0
Point3
18. Exercise: Attribute Assignment
• Recall, q gets name in p
>>> p = introcs.Point3(0,0,0)
>>> q = p
• Execute the assignments:
>>> p.x = 5.6
>>> q.x = 7.4
• What is value of p.x?
9/20/22 Objects 18
id4
p id4
q
A: 5.6
B: 7.4
C: id4
D: I don’t know
id4
x 0.0
y 0.0
z 0.0
Point3
5.6
CORRECT
x
19. Exercise: Attribute Assignment
• Recall, q gets name in p
>>> p = introcs.Point3(0,0,0)
>>> q = p
• Execute the assignments:
>>> p.x = 5.6
>>> q.x = 7.4
• What is value of p.x?
9/20/22 Objects 19
id4
p id4
q
A: 5.6
B: 7.4
C: id4
D: I don’t know
id4
x 0.0
y 0.0
z 0.0
Point3
5.6 7.4
CORRECT
x x
20. Objects Allow for Mutable Functions
• Mutable function: alters the parameters
§ Often a procedure; no return value
• Until now, this was impossible
§ Function calls COPY values into new variables
§ New variables erased with call frame
§ Original (global?) variable was unaffected
• But object variables are folder names
§ Call frame refers to same folder as original
§ Function may modify the contents of this folder
9/20/22 Objects 20
21. Example: Mutable Function Call
• Example:
def incr_x(q):
q.x = q.x + 1
>>> p = Point3(0,0,0)
>>> p.x
0.0
>>> incr_x(p)
>>> p.x
1.0
1
incr_x 2
id1
q
Global STUFF
Call Frame
id1
p
id1
0.0
…
Point3
x
2
9/20/22 Objects 21
22. Example: Mutable Function Call
• Example:
def incr_x(q):
q.x = q.x + 1
>>> p = Point3(0,0,0)
>>> p.x
0.0
>>> incr_x(p)
>>> p.x
1.0
1
incr_x
id1
q
Global STUFF
Call Frame
id1
p
id1
0.0
…
Point3
x
2
1.0
x
9/20/22 Objects 22
23. Example: Mutable Function Call
• Example:
def incr_x(q):
q.x = q.x + 1
>>> p = Point3(0,0,0)
>>> p.x
0.0
>>> incr_x(p)
>>> p.x
1.0
1
Global STUFF
Call Frame
id1
p
id1
0.0
…
Point3
x
2
1.0
x
ERASE WHOLE FRAME
Change
remains
9/20/22 Objects 23
24. Methods: Functions Tied to Objects
• Have seen object folders contain variables
§ Syntax: ⟨obj⟩.⟨attribute⟩ (e.g. p.x)
§ These are called attributes
• They can also contain functions
§ Syntax: ⟨obj⟩.⟨method⟩(⟨arguments⟩)
§ Example: p.clamp(-1,1)
§ These are called methods
• Visualizer will not show these inside folders
§ Will see why in November (when cover Classes)
9/20/22 Objects 24
25. Understanding Method Calls
• Object before the name is an implicit argument
• Example: distance
>>> p = Point3(0,0,0) # First point
>>> q = Point3(1,0,0) # Second point
>>> r = Point3(0,0,1) # Third point
>>> p.distance(r) # Distance between p, r
1.0
>>> q.distance(r) # Distance between q, r
1.4142135623730951
9/20/22 Objects 25
26. Recall: String Method Calls
• Method calls have the form
string.name(x,y,…)
• The string in front is an additional argument
§ Just one that is not inside of the parentheses
§ Why? Will answer this later in course.
method
name
arguments
argument
Are strings objects?
9/20/22 Objects 26
27. Surprise: All Values are Objects!
• Including basic values
§ int, float, bool, str
• Example:
>>> x = 1000
>>> id(x) 2.5
x
2.5
id5
id5
x
float
9/20/22 Objects 27
28. This Explains A Lot of Things
• Basic types act like classes
§ Conversion function is really a constructor
§ Remember constructor, type have same name
• Example:
>>> type(1)
<class 'int'>
>>> int('1')
1
• Design goals of Python 3
§ Wanted everything an object
§ Makes processing cleaner
• But makes learning harder
§ Objects are complex topic
§ Want to delay if possible
9/20/22 Objects 28
29. But Not Helpful to Think This Way
• Number folders are immutable
§ “Variables” have no names
§ No way to reach in folder
§ No way to change contents
>>> x = 1000
>>> y = 1000
>>> id(x)
4497040368
>>> id(y)
4497040400
>>> y = y+1
>>> id(y)
4497040432
1000
4497040368
4497040368
x
int Makes a brand
new int folder
9/20/22 Objects 29
30. But Not Helpful to Think This Way
• Number folders are immutable
§ “Variables” have no names
§ No way to reach in folder
§ No way to change contents
• Remember purpose of folder
§ Show how objects can be altered
§ Show how variables “share” data
§ This cannot happen in basic types
• So just ignore the folders
§ (The are just metaphors anyway)
>>> x = 1000
>>> y = 1000
>>> id(x)
4497040368
>>> id(y)
4497040400
>>> y = y+1
>>> id(y)
4497040432
9/20/22 Objects 30
31. Basic Types vs. Classes
Basic Types
• Built-into Python
• Refer to instances as values
• Instantiate with literals
• Are all immutable
• Can ignore the folders
Classes
• Provided by modules
• Refer to instances as objects
• Instantiate w/ constructors
• Can alter attributes
• Must represent with folders
9/20/22 Objects 31
In doubt? Use the Python Tutor
32. Where To From Here?
• Right now, just try to understand objects
§ All Python programs use objects
§ The object classes are provided by Python
• OO Programming is about creating classes
§ But we will not get to this until after Prelim 1
• Similar to the separation of functions
§ First learned to call functions (create objects)
§ Then how to define functions (define classes)
9/20/22 Objects 32