In Python, operator overloading is accomplished via "magic methods" -- specially named methods that begin and end with double underscore ("dunder"). Most Python developers know about __init__ and even __str__, but magic methods are used to accomplish many things in the Python world. In this talk, I introduce a number of these methods, and show how they can be used to make our objects more expressive.
The goal of this presentation is to broaden your knowledge of Python, exploring some concepts and techniques you might have never heard about. I won't go into too much detail, the goal is only to inspire you to research those features and patterns.
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.
Arrays In Python | Python Array Operations | EdurekaEdureka!
** Python Certification Training: https://www.edureka.co/python **
This Edureka PPT on 'Arrays in Python' will help you establish a strong hold on all the fundamentals in the Python programming language. Below are the topics covered in this PPT:
What is an array?
Is python list same as an array?
How to create arrays in python?
Accessing array elements
Basic array operations
- Finding the length of an array
- Adding Elements
- Removing elements
- Array concatenation
- Slicing
- Looping
Python Tutorial Playlist: https://goo.gl/WsBpKe
Blog Series: http://bit.ly/2sqmP4s
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
The tutorial will introduce you to Python Packages. This Python basic tutorial will help you understand creating a Python package. You will understand the example of a Python Package. After that, you will understand different ways to access Python Packages. Further, the demonstration will educate you on how to create Python Package.
The goal of this presentation is to broaden your knowledge of Python, exploring some concepts and techniques you might have never heard about. I won't go into too much detail, the goal is only to inspire you to research those features and patterns.
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.
Arrays In Python | Python Array Operations | EdurekaEdureka!
** Python Certification Training: https://www.edureka.co/python **
This Edureka PPT on 'Arrays in Python' will help you establish a strong hold on all the fundamentals in the Python programming language. Below are the topics covered in this PPT:
What is an array?
Is python list same as an array?
How to create arrays in python?
Accessing array elements
Basic array operations
- Finding the length of an array
- Adding Elements
- Removing elements
- Array concatenation
- Slicing
- Looping
Python Tutorial Playlist: https://goo.gl/WsBpKe
Blog Series: http://bit.ly/2sqmP4s
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
The tutorial will introduce you to Python Packages. This Python basic tutorial will help you understand creating a Python package. You will understand the example of a Python Package. After that, you will understand different ways to access Python Packages. Further, the demonstration will educate you on how to create Python Package.
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
Classes and Object-oriented Programming:
Classes: Creating a Class, The Self Variable, Constructor, Types of Variables, Namespaces, Types of Methods (Instance Methods, Class Methods, Static Methods), Passing Members of One Class to Another Class, Inner Classes
Inheritance and Polymorphism: Constructors in Inheritance, Overriding Super Class Constructors and Methods, The super() Method, Types of Inheritance, Single Inheritance, Multiple Inheritance, Method Resolution Order (MRO), Polymorphism, Duck Typing Philosophy of Python, Operator Overloading, Method Overloading, Method Overriding
Abstract Classes and Interfaces: Abstract Method and Abstract Class, Interfaces in Python, Abstract Classes vs. Interfaces,
This presentation educates you about objectives of python with example syntax, OOP Terminology, Creating Classes, Creating Instance Objects, Accessing Attributes and Built-In Class Attributes.
YouTube Link: https://youtu.be/7GXaobCrBb4
** Python Certification Training: https://www.edureka.co/python **
This Edureka PPT on 'Python Modules' will help you understand the concept of modules in python, why and how we can use modules in python. Below are the topics covered in this PPT:
What Is A Python Module?
How To Create A Python Module?
How To Call A Python Module?
Built-in Modules In Python
Demo
Python Tutorial Playlist: https://goo.gl/WsBpKe
Blog Series: http://bit.ly/2sqmP4s
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Castbox: https://castbox.fm/networks/505?country=in
A function is a set of statements that take inputs, do some specific computation and produces output. The idea is to put some commonly or repeatedly done task together and make a function, so that instead of writing the same code again and again for different inputs, we can call the function.
Python provides built-in functions like print(), etc. but we can also create your own functions. These functions are called user-defined functions.
All data values in Python are encapsulated in relevant object classes. Everything in Python is an object and every object has an identity, a type, and a value. Like another object-oriented language such as Java or C++, there are several data types which are built into Python. Extension modules which are written in C, Java, or other languages can define additional types.
To determine a variable's type in Python you can use the type() function. The value of some objects can be changed. Objects whose value can be changed are called mutable and objects whose value is unchangeable (once they are created) are called immutable.
OOPS concepts are one of the most important concepts in high level languages. Here in this PPT we will learn more about Object oriented approach in python programming which includes details related to classes and objects, inheritance, dat abstraction, polymorphism and many more with examples and code.
Inheritance and Polymorphism in Python. Inheritance is a mechanism which allows us to create a new class – known as child class – that is based upon an existing class – the parent class, by adding new attributes and methods on top of the existing class.
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
Classes and Object-oriented Programming:
Classes: Creating a Class, The Self Variable, Constructor, Types of Variables, Namespaces, Types of Methods (Instance Methods, Class Methods, Static Methods), Passing Members of One Class to Another Class, Inner Classes
Inheritance and Polymorphism: Constructors in Inheritance, Overriding Super Class Constructors and Methods, The super() Method, Types of Inheritance, Single Inheritance, Multiple Inheritance, Method Resolution Order (MRO), Polymorphism, Duck Typing Philosophy of Python, Operator Overloading, Method Overloading, Method Overriding
Abstract Classes and Interfaces: Abstract Method and Abstract Class, Interfaces in Python, Abstract Classes vs. Interfaces,
This presentation educates you about objectives of python with example syntax, OOP Terminology, Creating Classes, Creating Instance Objects, Accessing Attributes and Built-In Class Attributes.
YouTube Link: https://youtu.be/7GXaobCrBb4
** Python Certification Training: https://www.edureka.co/python **
This Edureka PPT on 'Python Modules' will help you understand the concept of modules in python, why and how we can use modules in python. Below are the topics covered in this PPT:
What Is A Python Module?
How To Create A Python Module?
How To Call A Python Module?
Built-in Modules In Python
Demo
Python Tutorial Playlist: https://goo.gl/WsBpKe
Blog Series: http://bit.ly/2sqmP4s
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Castbox: https://castbox.fm/networks/505?country=in
A function is a set of statements that take inputs, do some specific computation and produces output. The idea is to put some commonly or repeatedly done task together and make a function, so that instead of writing the same code again and again for different inputs, we can call the function.
Python provides built-in functions like print(), etc. but we can also create your own functions. These functions are called user-defined functions.
All data values in Python are encapsulated in relevant object classes. Everything in Python is an object and every object has an identity, a type, and a value. Like another object-oriented language such as Java or C++, there are several data types which are built into Python. Extension modules which are written in C, Java, or other languages can define additional types.
To determine a variable's type in Python you can use the type() function. The value of some objects can be changed. Objects whose value can be changed are called mutable and objects whose value is unchangeable (once they are created) are called immutable.
OOPS concepts are one of the most important concepts in high level languages. Here in this PPT we will learn more about Object oriented approach in python programming which includes details related to classes and objects, inheritance, dat abstraction, polymorphism and many more with examples and code.
Inheritance and Polymorphism in Python. Inheritance is a mechanism which allows us to create a new class – known as child class – that is based upon an existing class – the parent class, by adding new attributes and methods on top of the existing class.
A brief introduction to functional programming.
Even if slides present some simple Python code, functional programming patterns applies to other languages too.
در این جلسه به بررسی بحث برنامه نویسی شی گرا و کلاس ها در پایتون پرداختیم
PySec101 Fall 2013 J7E1 By Mohammad Reza Kamalifard
Talk About:
Object oriented programming and Classes in Python
Code Like Pythonista
Beautifully made PPT.
Ref. http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html
Image ref : https://pixabay.com/ko/ and https://morguefile.com/
licensed under a Creative Commons Attribution/Share-Alike (BY-SA) license.
An object oriented concept in python is detailed for the students or anyone who aspire to learn more powerful concept that helps in developing software or any web development to the persons who work in a tech filed
Why is big data all the rage? What is this "data science" that people are talking about? Why do I care — as a customer, and as someone who works at a company generating data? In this talk, I present the case for models, and how we can use data science to create and use models of our customers and the society around us.
PostgreSQL is a well-known relational database. But in the last few years, it has gained capabilities that previously belonged only to "NoSQL" databases. In this talk, I describe several of PostgreSQL that give it such capabilities.
What can Ruby learn from Python (and vice versa)?Reuven Lerner
Ruby and Python are similar programming languages in many ways. But each has made different design decisions that affect how programmers in these languages think and work. In this talk, I contrast Ruby and Python, and some of the ways in which the languages differ.
Functional Python Webinar from October 22nd, 2014Reuven Lerner
Slides from my free functional Python webinar, given on October 22nd, 2014. Discussion included functional programming as a perspective, passing functions as data, and writing programs that take functions as parameters. Includes (at the end) a coupon for my new ebook, Practice Makes Python.
Since the beginning of software, we have bundled frequently-used functionality into libraries -- both our own, and those created by third parties. APIs tell software developers how to use a library, and make it possible for developers to treat libraries as black boxes, considering only what the library does, not how it does it.
Today, as software moves increasingly to the Web, APIs and libraries are also moving to the Web. This means that you can now outsource, by means of Web APIs, a huge amount of your application's functionality.
What does this mean for software developers? What does this mean for the future of software development? In this talk, I describe the past, present, and future of APIs, and how I believe the Web is changing the landscape.
Active Record 4.0 includes all sorts of exciting support for PostgreSQL! In this presentation, I show many of these improvements, and discuss why these are important for Web developers. If you haven't yet adopted PostgreSQL, now might be a great time and chance to do so.
Intro to cloud computing — MegaCOMM 2013, JerusalemReuven Lerner
What is cloud computing? This is an introduction that I gave at MegaCOMM 2013, a conference for technical writers in Jerusalem. The talk describes how the combination of Internet access, virtualization, and open source have made computing a utility that we can turn on and off at will -- similar in some ways to electricity, water, and other utilities with which we're familiar.
The latest version of my PostgreSQL introduction for IL-TechTalks, a free service to introduce the Israeli hi-tech community to new and interesting technologies. In this talk, I describe the history and licensing of PostgreSQL, its built-in capabilities, and some of the new things that were added in the 9.1 and 9.2 releases which make it an attractive option for many applications.
When you're writing a Ruby on Rails application, certain decisions seem appropriate and good at the beginning, but come back to bite you later on. In this talk, I list 20 different "traps," things that seem appealing, but which you should think twice before doing. The talk is based on my experience teaching Ruby and Rails classes to many people over the years, and was a presentation at the "Rails Israel 2012" conference held in Tel Aviv.
Modern Web technologies (and why you should care): Megacomm, Jerusalem, Febru...Reuven Lerner
My talk from the Megacomm 2012 conference in Jerusalem, on February 16th, 2012. I describe the fundamental underpinnings of the Web, how things have changed on both the browser and server sides, and what these technologies mean for users..
Git talk from Open 2011 conference in IsraelReuven Lerner
Git is an open source, distributed version control system that changes the way that you think about version control. In this lecture, I present some of the reasons why you would use a version-control system, and some of the compelling reasons why you should consider Git.
Dynamic languages, for software craftmanship groupReuven Lerner
Reuven Lerner's talk about dynamic programming languages in general, and about Ruby in particular. Why would you want to use a dynamic language? What can you do with one that isn't possible (or easy) with a static language?
Modern Web Technologies — Jerusalem Web Professionals, January 2011Reuven Lerner
What's the current state of Web technologies, and how does it affect professionals creating Web applications? In this talk, I survey the latest trends in Web technologies, and where I believe they're going in the near future.
An introductory, overview talk about PostgreSQL, given at the Database 2011 conference in January, in Israel. I point to a number of PostgreSQL features that make it a compelling choice in many different contexts.
Slides from a lecture I just gave on ActiveRecord 2.3. Describes configuration, methods, CRUD, finders, updating, associations, and a bunch of things that I wish I had known when I started with ActiveRecord.
Ruby is an object-oriented programming language; that much, everyone knows. But Ruby's objects work very differently from many other languages, especially if you're coming from a complied, statically typed language. In this lecture, I'll review the surprisingly simple rules that govern Ruby's objects. I discuss methods, classes, instances, and modules, and how these various pieces fit together into an integrated whole -- including such topics as inheritance, instance variables, class variables, mixins, and "include" vs. "extend".
Slides from a talk I gave about using the Ruby on Rails console (and irb) to develop Web applications. Describes the features of the console, and how you might want to use it.
Reuven Lerner's presentation from Open Ruby Day in Herzliya, Israel on June 27th, 2010. I covered a few tools that are not part of Rails, but which help you with deployment,
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on the notifications, alerts, and approval requests using Slack for Bonterra Impact Management. The solutions covered in this webinar can also be deployed for Microsoft Teams.
Interested in deploying notification automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
In this presentation, we examine the challenges and limitations of relying too heavily on PHP frameworks in web development. We discuss the history of PHP and its frameworks to understand how this dependence has evolved. The focus will be on providing concrete tips and strategies to reduce reliance on these frameworks, based on real-world examples and practical considerations. The goal is to equip developers with the skills and knowledge to create more flexible and future-proof web applications. We'll explore the importance of maintaining autonomy in a rapidly changing tech landscape and how to make informed decisions in PHP development.
This talk is aimed at encouraging a more independent approach to using PHP frameworks, moving towards a more flexible and future-proof approach to PHP development.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Search and Society: Reimagining Information Access for Radical FuturesBhaskar Mitra
The field of Information retrieval (IR) is currently undergoing a transformative shift, at least partly due to the emerging applications of generative AI to information access. In this talk, we will deliberate on the sociotechnical implications of generative AI for information access. We will argue that there is both a critical necessity and an exciting opportunity for the IR community to re-center our research agendas on societal needs while dismantling the artificial separation between the work on fairness, accountability, transparency, and ethics in IR and the rest of IR research. Instead of adopting a reactionary strategy of trying to mitigate potential social harms from emerging technologies, the community should aim to proactively set the research agenda for the kinds of systems we should build inspired by diverse explicitly stated sociotechnical imaginaries. The sociotechnical imaginaries that underpin the design and development of information access technologies needs to be explicitly articulated, and we need to develop theories of change in context of these diverse perspectives. Our guiding future imaginaries must be informed by other academic fields, such as democratic theory and critical theory, and should be co-developed with social science scholars, legal scholars, civil rights and social justice activists, and artists, among others.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
2. Methods
• We define methods on a class
• We then invoke them via an instance
• (We're going to ignore static and class methods)
• The method is found via attribute lookup:
• Object -> object's class -> super -> … -> object
3. Method naming
• We can use whatever method names we want!
• So long as we take "self" as a parameter, Python
doesn't really dictate the names that we use
4. Except.
• Except for the so-called "magic methods"
• These methods are rarely called directly!
• Rather, they're called automatically by Python,
typically as the result of invoking an operator
5. __init__
• __init__ is the first method that many Python
programmers learn about.
• It's not really a constructor, since the new object
already exists when __init__ is invoked.
6. __len__
• When you call len(x), it looks for __len__
• Don't call __len__ directly; rather use len()
• You can, of course, return whatever you want,
which is the point — whatever is appropriate for
your object
7. Example
class Book(object):
def __init__(self, title, author, num_pages):
self.title = title
self.author = author
self.num_pages = num_pages
def __len__(self):
return self.num_pages
>>> b = Book('The Terrible Two', 'Mac Barnett', 224)
>>> len(b)
224
8. Really magic methods
• Most people who learn about Python object learn
about __init__, __len__, and probably __repr__ and
__str__.
• But the magic methods go way beyond that!
9. __add__
• Add two elements together
• __add__ gets two parameters
• self
• Another object
• How do you add them? That's up to you!
• Typically, you'll return a new instance of the same
class
10. Example
class Foo(object):
def __init__(self, x):
self.x = x
def __add__(self, other):
return Foo(self.x + other.x)
def __repr__(self):
return "Instance of f, x = {}".format(self.x)
f1 = Foo(10)
f2 = Foo(20)
print(f1 + f2)
11. __iadd__
• We can also address what happens when += is
invoked
• This is not the same as __add__!
• The expectation is that you'll change the state of
the current object, and then return self.
12. Example
class Foo(object):
def __init__(self, x):
self.x = x
def __iadd__(self, other):
self.x += other.x
return self
def __repr__(self):
return "Instance of f, x = {}".format(self.x)
f1 = Foo(10)
f2 = Foo(20)
f1 += f2
print("Now f1 = {}".format(f1))
13. Making __add__ flexible
• Remember, the second argument can be anything
• If we want, we can play games with that —
checking for attributes
14. Example
class Foo(object):
def __init__(self, x):
self.x = x
def __add__(self, other):
if hasattr(other, 'x'):
return Foo(self.x + other.x)
else:
return Foo(self.x + other)
def __repr__(self):
return "Instance of f, x = {}".format(self.x)
f1 = Foo(10)
f2 = Foo(20)
print("f1 + f2 = {}".format(f1 + f2))
print("f1 + 10 = {}".format(f1 + 50))
15. Reversible?
• What if we now say
print("10 + f1 = {}".format(50 + f1))
• What will Python do?
16. f1 + 10 = Instance of f, x = 60
Traceback (most recent call last):
File "./foo.py", line 29, in <module>
print("10 + f1 = {}".format(50 + f1))
TypeError: unsupported operand type(s) for
+: 'int' and 'Foo'
17. __radd__
• Auto-reversing: We get self and other, and now
invoke our previously defined __add__:
def __radd__(self, other):
return self.__add__(other)
18. How does this work?
• Python tries to do it the usual way
• It gets NotImplemented back
• Not an exception!
• An instance of Not ImplementedType!
• Python then tries (in desperation) to turn things
around… and thus, __radd__
19. Type conversions
• You probably know about __str__ already
• But what about __int__? Or even __hex__?
23. But with __nonzero__…
class Foo(object):
def __init__(self, x):
self.x = x
def __nonzero__(self):
return bool(self.x)
>>> f = Foo(1)
>>> bool(f)
True
>>> f = Foo(0)
>>> bool(f)
False
24. Format
• Originally, Python used the % syntax for pseudo-
interpolation:
name = 'Reuven'
print('Hello %s' % name)
• But there are lots of problems with it, so it's better
to use str.format
28. Custom formats
• It turns out that our objects can also handle these
custom formats!
• If we define __format__ on our object, then it'll get
the format code (i.e., whatever comes after the :)
• We can then decide what to do with it
29. class Person(object):
def __init__(self, given, family):
self.given = given
self.family = family
def __format__(self, format):
if format == 'familyfirst':
return "{} {}".format(self.family, self.given)
elif format == 'givenfirst':
return "{} {}".format(self.given, self.family)
else:
return "BAD FORMAT CODE"
30. Using it
>>> p = Person('Reuven', 'Lerner')
>>> "Hello, {}".format(p)
'Hello, BAD FORMAT CODE'
>>> "Hello, {:familyfirst}".format(p)
'Hello, Lerner Reuven'
>>> "Hello, {:givenfirst}".format(p)
'Hello, Reuven Lerner'
31. Pickle
• Pickle allows you to serialize, or marshall objects
• You can then store them to disk, or send them on
the network
• Pickle works with most built-in Python data types,
and classes built on those types
33. Custom pickling
• Define some magic methods (of course) to
customize your pickling:
• __getstate__ returns a dictionary that should reflect
the object. Want to add to (or remove from) what is
being pickled? Just modify a copy of self.__dict__
and return it!
• Don't modify the dictionary itself…
34. Example
class Foo(object):
def __init__(self, x):
self.x = x
def __getstate__(self):
odict = self.__dict__.copy()
odict['y'] = self.x * 2
return odict
>>> f = Foo(10)
>>> p = pickle.dumps(f)
>>> new_f = pickle.loads(p)
>>> vars(new_f)
{'x': 10, 'y': 20}
35. Equality
• What makes two object equal?
• By default in Python, they're only equal if their ids
are equal
• (Yes, every object has a unique ID number — use
the "id" function to find it!)
• You change this by defining __eq__!
36. Changing equality
class Foo(object):
def __init__(self, x):
self.x = x
def __eq__(self, other):
return self.x == other.x
>>> f1 = Foo(10)
>>> f2 = Foo(10)
>>> f1 == f2
True
37. Hashing
• If two objects are equal, then maybe they should
hash to the same value, right?
• We can set the __hash__ attribute to be a method
that returns whatever we want
38. Playing with __hash__
class Foo(object):
def __init__(self, x):
self.x = x
def __hash__(self):
return hash(self.x)
>>> f = Foo('a')
>>> hash(f)
12416037344
>>> hash('a')
12416037344
f = Foo(1)
>>> hash(f)
1
39. Messing around with
hashing
• What if we have __hash__ return a random number
each time?
• That will have some interesting consequences…
40. Questions?
• Follow me: @reuvenmlerner
• Buy my book, "Practice Makes Python"
• 10% off with offer code "webinar"
• Get my newsletter: http://lerner.co.il/newsletter
• Read my blog: http://blog.lerner.co.il/
• Learn a bit: http://DailyTechVideo.com/