Object Oriented programming in Python.
Originally part 3 of a 4 lectures seminar for the Networking class of the Computer Science course at the University of Parma
Slides from Advaned Python lectures I gave recently in Haifa Linux club
Advanced python, Part 1:
- Decorators
- Descriptors
- Metaclasses
- Multiple inheritance
In JS: CLASS <=> Constructor FN
new FN() => FN() { this }
FN = CLASS (FN = FN, FN = DATA)
Objects
Prototype / __proto__
Inheritence
Rewriting / Augmenting
built in objects
My JSConf.eu talk about next-gen JavaScript metaprogramming features, starting with ES5's new Object APIs and then focusing on the forthcoming Proxy object, approved for the next ECMA-262 Edition. This is beautiful work from Tom Van Cutsem and Mark Miller, with Andreas Gal helping on the implementation front -- proxies are already shipping in Firefox 4 betas.
A brief look at the new features coming in Javascript ES6:
- Scope and control
- Iterators and Generators
- Collections
- Typed objects
- Direct proxies
- Template strings
- API improvements
- Modularity
Symfony World - Symfony components and design patternsŁukasz Chruściel
There are so many Symfony components already, and they have some pretty neat perks. But have you seen them in action?
Design patterns are not a silver bullet. They will never resolve your problem on their own. On the other hand, design patterns provide a common ground for developers without going into details and could be used as building bricks to solve some more advanced problems.
During my presentation, I will take a closer look and explain the appliance of selected design patterns. What is more, I will take advantage of the Symfony ecosystem to implement them with ease.
I will do the presentation on sample code that developers will understand at all levels of expertise.
Programmation fonctionnelle en JavaScriptLoïc Knuchel
La programmation fonctionnelle permet de faire du code plus modulaire, avec moins de bugs et de manière plus productive !!!
Cette présentation montre comment la programmation fonctionnelle peut tenir se promesse et comment l'appliquer avec JavaScript.
Performance and testing are just one aspect of code, to really be successful your code needs to be readable, maintainable and generally easier to comprehend and work with. This talk draws from my own experience in applying the techniques of object calisthenics and code readability, within an existing team. It will help you identify trouble areas, learn how to refactor them and train you to write better code in future projects avoiding common pitfalls.
Slides from Advaned Python lectures I gave recently in Haifa Linux club
Advanced python, Part 1:
- Decorators
- Descriptors
- Metaclasses
- Multiple inheritance
In JS: CLASS <=> Constructor FN
new FN() => FN() { this }
FN = CLASS (FN = FN, FN = DATA)
Objects
Prototype / __proto__
Inheritence
Rewriting / Augmenting
built in objects
My JSConf.eu talk about next-gen JavaScript metaprogramming features, starting with ES5's new Object APIs and then focusing on the forthcoming Proxy object, approved for the next ECMA-262 Edition. This is beautiful work from Tom Van Cutsem and Mark Miller, with Andreas Gal helping on the implementation front -- proxies are already shipping in Firefox 4 betas.
A brief look at the new features coming in Javascript ES6:
- Scope and control
- Iterators and Generators
- Collections
- Typed objects
- Direct proxies
- Template strings
- API improvements
- Modularity
Symfony World - Symfony components and design patternsŁukasz Chruściel
There are so many Symfony components already, and they have some pretty neat perks. But have you seen them in action?
Design patterns are not a silver bullet. They will never resolve your problem on their own. On the other hand, design patterns provide a common ground for developers without going into details and could be used as building bricks to solve some more advanced problems.
During my presentation, I will take a closer look and explain the appliance of selected design patterns. What is more, I will take advantage of the Symfony ecosystem to implement them with ease.
I will do the presentation on sample code that developers will understand at all levels of expertise.
Programmation fonctionnelle en JavaScriptLoïc Knuchel
La programmation fonctionnelle permet de faire du code plus modulaire, avec moins de bugs et de manière plus productive !!!
Cette présentation montre comment la programmation fonctionnelle peut tenir se promesse et comment l'appliquer avec JavaScript.
Performance and testing are just one aspect of code, to really be successful your code needs to be readable, maintainable and generally easier to comprehend and work with. This talk draws from my own experience in applying the techniques of object calisthenics and code readability, within an existing team. It will help you identify trouble areas, learn how to refactor them and train you to write better code in future projects avoiding common pitfalls.
Introducing FAIMS Media Template Apps, a suite of automated apps, for PC & Mobile to simplify and empower from Multinational to SME Social Media Marketing
Vortrag von Britta Heer und Christian Lee Rottmann auf der AllFacebook Marketing Conference 2014 in Berlin.
Mehr Informationen:
http://conference.allfacebook.de/
La Fresa (fragaria SPP) es una fruta de distribución mundial, muy apreciada para consumo fresco y la elaboraciòn de postres, debido a sus cualides de color, aroma y acidez, ademas es una fruta rica en vitamina A y C.
El manejo agronómico del cultivo comprende las etapas de viviero, instalación del cultivo, mantenimiento y cosecha. Para un buen desarrollo de la fresa es necesario conocer y manejar la tecnología desde la siembra de las plantas madres hasta la cosecha, con el fin de obtener buenos rendimientos.
Understanding how and why students use lecture capturesMatt Cornock
A recap of my ALT-C presentation on the research into students' use of lecture captures from a qualitative and context-centred perspective. Presentation to the TEL Research Group at the University of Liverpool. 6 June 2016.
How students use lecture captures as part of their studyingMatt Cornock
Nine study workflows that use lecture capture to enhance student learning. Suggestions and quotes from students interviewed as part of our lecture capture research in 2015, updated based upon focus group feedback Spring 2016. Further information at http://bit.ly/replay-research-nov15
Slides contain selectively and subjectively choosen topics related with development application in Django framework like: class-based views, signals, customizing User model after 1.5 version released, database migration and queuing tasks using Celery and RabbitMQ.
The Rule of 10,000 Spark Jobs - Learning from Exceptions and Serializing Your...Matthew Tovbin
Spark + AI Summit, 2019 - Mastering complex software stacks, such as Spark or Hadoop, is a challenging process. Incompatible dependencies, new programming paradigms, runtime errors, outdated documentation, scaling, tuning - this is just a short list of skills we must acquire. How do we make sure that we are not wasting time and making progress learning? How do we share our knowledge efficiently? This talk walks you through a journey of scaling Salesforce Einstein AI platform to serve 6B+ predictions per day and provides you with a scale to measure learning progress.
The Rule of 10,000 Spark Jobs: Learning From Exceptions and Serializing Your ...Databricks
Mastering complex software stacks, such as Spark or Hadoop, is a challenging process. Incompatible dependencies, new programming paradigms, runtime errors, outdated documentation, scaling, tuning - this is just a short list of skills we must acquire. How do we make sure that we are not wasting time and making progress learning? How do we share our knowledge efficiently? This talk walks you through a journey of scaling Salesforce Einstein AI platform to serve 3B+ predictions per day and provides you with a scale to measure learning progress.
Speaker: Matthew Tovbin
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
Ever seen a code base where understanding a simple method meant jumping through tangled class hierarchies? We all have! And while "Favor composition over inheritance!" is almost as old as object-oriented programming, strictly avoiding all types of subclassing leads to verbose, un-Pythonic code. So, what to do?
The discussion on composition vs. inheritance is so frustrating because far-reaching design decisions like this can only be made with the ecosystem in mind – and because there's more than one type of subclassing!
Let's take a dogma-free stroll through the types of subclassing through a Pythonic lens and untangle some patterns and trade-offs together. By the end, you'll be more confident in deciding when subclassing will make your code more Pythonic and when composition will improve its clarity.
Not so long ago Microsoft announced a new language trageting on front-end developers. Everybody's reaction was like: Why?!! Is it just Microsoft darting back to Google?!
So, why a new language? JavaScript has its bad parts. Mostly you can avoid them or workaraund. You can emulate class-based OOP style, modules, scoping and even run-time typing. But that is doomed to be clumsy. That's not in the language design. Google has pointed out these flaws, provided a new language and failed. Will the story of TypeScript be any different?
Datagrids with Symfony 2, Backbone and BackgridGiorgio Cefaro
These are the slides of the code-centered presentation I did with Eugenio Pombi at the Javascript User Group Roma and the PHP User Group Roma.
In this presentation we try to show many powerful features of symfony2 and its bundles to work as a backend system for single page applications.
On the client side we describe how we made a javascript editable grid using Backbone.js and its plugin for grids Backgrid.js.
Datagrids with Symfony 2, Backbone and Backgrideugenio pombi
These are the slides of the code-centered presentation I did with Giorgio Cefaro at the Javascript UserGroup Roma and the PHP User Group Roma.
In this presentation we try to show many powerful features of symfony2 and its bundles to work as a backend system for single page applications.
On the client side we describe how we made a javascript editable grid using Backbone.js and its plugin for grids Backgrid.js.
An introductory-to-mid level to presentation to complex network analysis: network metrics, analysis of online social networks, approximated algorithms, memorization issues, storage.
Python is a high level language focused on readability. The Python community developed the concept of "Pythonic Code", requiring not only semantic correctness, but also conformity to universally acknowledged stylistic criteria.
A pre-requisite to write pythonic code is to write idiomatic code. Using the right idioms is a matter of acquired taste and experience, however, some idioms are quite easy to learn.
This presentation focuses on some of these idioms and other stylistic criteria:
* for vs. while
* iterators, itertools
* code conventions (space invaders)
* avoid default values bugs
* first order functions
* internal/external iterators
* substituting the switch statement
* properties, attributes, read only objects
* named tuples
* duck typings
* bits of metaprogramming
* exception management: LBYL vs. EAFP
Simple presentation on Twisted fundamentals.
Originally part 4 of a 4 lectures seminar for the Networking class of the Computer Science course at the University of Parma
A simple introduction to the Python programming language. In Italian. OLD: superseeded by Pycrashcourse 3.1.
Originally part 1 of a 4 lectures seminar for the Networking class of the Computer Science course at the University of Parma
A simple introduction to the Python programming language. In Italian. OLD: superseeded by Pycrashcourse 3.1.
Originally presented during the Networking class of the Computer Science course at the University of Parma
Object Oriented programming in Python.
Originally part 2 of a 4 lectures seminar for the Networking class of the Computer Science course at the University of Parma
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.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
Let's dive deeper into the world of ODC! Ricardo Alves (OutSystems) will join us to tell all about the new Data Fabric. After that, Sezen de Bruijn (OutSystems) will get into the details on how to best design a sturdy architecture within ODC.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
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.
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
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
2. Aumentare il dinamismo
Python offre come builtin getattr, setattr e
hasattr
f.foo getattr(f, ‘foo’)
f.foo = 4 setattr(f, ‘foo’, 4)
hasattr controlla solo se c’è l’attributo
Questo vuole dire che possiamo chiedere
un attributo a runtime conoscendone il
nome
Forte capacità di introspezione (assieme al
3. Esempio
class Capsule(object):
def __init__(self, obj):
self.obj = obj
def get(self, attribute_path):
parts = attribute_path.split('.')
current_obj = self.obj
for attribute in parts:
current_obj = getattr(current_obj, attribute)
return current_obj
if __name__ == "__main__":
d = datetime.date(1983, 7, 1)
e = Capsule(Employee('Enrico Franchi', d))
print e.get('birth_date.month')
4. Ripasso MRO
Sia a oggetto di tipo A, sottoclasse di B e
C
a.foo cerca nell’ordine:
1.fra gli attributi dell’oggetto a
2.fra gli attributi dell’oggetto classe A
3.fra gli attributi dell’oggetto classe B
4.fra gli attributi dell’oggetto classe C
Se non viene trovato, viene lanciato
AttributeError
5. Eppure...
Di fatto prima di lanciare AttributeError, si
vede se è disponibile un metodo
__getattr__(self, name)
In questo caso viene passato il nome
dell’attributo come stringa (in name)
Il corpo di __getattr__ può specificare cosa
ritornare (o se lanciare eccezione)
NB: siccome i metodi sono anche attributi,
funziona anche con loro
Per i “PRO” ci sono anche i descrittori...
6. Esempio
class Capsule(object):
def __init__(self, obj):
self.obj = obj
def get(self, attribute_path):
parts = attribute_path.split('.')
current_obj = self.obj
for attribute in parts:
current_obj = getattr(current_obj, attribute)
return current_obj
def __getattr__(self, attribute):
return getattr(self.obj, attribute)
7. Esempio
class Capsule(object):
def __init__(self, obj):
self.obj = obj
def get(self, attribute_path):
parts = attribute_path.split('.')
current_obj = self.obj
for attribute in parts:
current_obj = getattr(current_obj, attribute)
return current_obj
def __getattr__(self, attribute):
return getattr(self.obj, attribute)
Facile delegare...
(pensate un po’ al decorator pattern...)
8. Esempio
class Enum(object):
def __init__(self, *args, **kargs):
self._enums = dict(((name, i) for i, name in enumerate(args)))
min_val, max_val = 0, len(args)
for k, v in kargs.iteritems():
if min_val < v < max_val:
raise ValueError, ('Value %s already specified' % v)
else:
self._enums[k] = v
def __getattr__(self, name):
try:
return self._enums[name]
except KeyError:
raise AttributeError
9. Esempio
class Enum(object):
def __init__(self, *args, **kargs):
self._enums = dict(((name, i) for i, name in enumerate(args)))
min_val, max_val = 0, len(args)
for k, v in kargs.iteritems():
if min_val < v < max_val:
raise ValueError, ('Value %s already specified' % v)
else:
self._enums[k] = v
def __getattr__(self, name):
try:
return self._enums[name]
except KeyError:
raise AttributeError
Per Enum fatte a modo, qui.
Meglio ancora le named tuples.
10. Funzioni create a runtime
class Collection(object):
def __init__(self, l=None):
self.buf = l or []
def find(self, **kargs):
temp_buf = self.buf
for k, v in kargs.iteritems():
temp_buf = [item for item in temp_buf
if getattr(item, k) == v]
return temp_buf
11. Funzioni create a runtime
class Collection(object):
def __init__(self, l=None):
self.buf = l or []
def find(self, **kargs):
temp_buf = self.buf
for k, v b1 kargs.iteritems():
in = book.Book('Python in a Nutshell', 'Alex Martelli')
temp_buf = [item for item in temp_buf 'Alex Martelli')
b2 = book.Book('Python Cookbook',
b3 if getattr(item, k) == v]
= book.Book('Python', 'Marco Beri')
return temp_buf
b4 = book.Book('Sviluppare applicazioni web con Django',
'Marco Beri')
b5 = book.Book('Espressioni Regolari', 'Marco Beri')
c = Collection([b1, b2, b3, b4, b5])
for b in c.find(title='Python', author='Marco Beri'):
print b
12. Funzioni create a runtime
class Collection(object):
def __init__(self, l=None):
self.buf = l or []
def find(self, **kargs):
temp_buf = self.buf
for k, v in kargs.iteritems():
temp_buf = [item for item in temp_buf
if getattr(item, k) == v]
return temp_buf
@classmethod
def add_method(cls, func, name):
func.im_class = cls
func.im_func = func
func.im_self = None
func.func_name = name
setattr(cls, name, func)
14. __getattr__ avanzato
def __getattr__(self, name):
if name.startswith('find_by_'):
key = name[8:]
def _aux(self, value):
return Collection.find(self, **{key : value})
Collection.add_method(_aux, name)
return getattr(self, name)
else: raise TypeError
Creiamo una funzione a runtime
15. __getattr__ avanzato
def __getattr__(self, name):
if name.startswith('find_by_'):
key = name[8:]
def _aux(self, value):
return Collection.find(self, **{key : value})
Collection.add_method(_aux, name)
return getattr(self, name)
else: raise TypeError
Creiamo una funzione a runtime
La facciamo diventare metodo della classe
16. __getattr__ avanzato
def __getattr__(self, name):
if name.startswith('find_by_'):
key = name[8:]
def _aux(self, value):
return Collection.find(self, **{key : value})
Collection.add_method(_aux, name)
return getattr(self, name)
else: raise TypeError
Creiamo una funzione a runtime
La facciamo diventare metodo della classe
Ora getattr la può trovare (nella fase 2.) e
restituisce il metodo
17. __getattr__ avanzato
def __getattr__(self, name):
if name.startswith('find_by_'):
key = name[8:]
def _aux(self, value):
return Collection.find(self, **{key : value})
Collection.add_method(_aux, name)
return getattr(self, name)
else: raise TypeError
Creiamo una funzione a runtime
for b in c.find_by_author('Marco Beri'):
La facciamo diventare metodo della classe
print b
for b in c.find_by_author('Alex Martelli'):
Ora getattr la può trovare (nella fase 2.) e
print b
restituisce il metodo
18. Server side modules
Scriviamo un gestore (“handler”) che
contiene il codice per implementare il
protocollo
Creiamo un server cui passiamo l’handler
Il server gestisce i dettagli, noi il protocollo
Server prefabbricati:
TCPServer ForkingUDPServer
UDPServer ThreadingTCPServe
r
ForkingTCPServer
19. Handler
Per ogni richiesta viene creato un nuovo
handler
Alcuni server (Threading, Forking)
gestiscono concorrenza, gli altri in serie
con un server Forking di base le modifiche
allo stato dei figli non si riflette sul padre
con un Threading bisogna gestire lock,
etc...
20. Handler (2)
Si sottoclassa un handler
(SocketServer.BaseRequestHandler)
Si “overridda” handle(self) [e altro se
opport.]
Si hanno come variabili d’istanza
self.request: la richiesta (socket)
self.client_address: guess...
self.server: un’istanza del server
Entro certi limiti, si è indipendenti dal
21. Handler (2)
Si sottoclassa un handler
(SocketServer.BaseRequestHandler)
Si “overridda” handle(self) [e altro se
opport.]
Chi scrive trova
Si hanno come variabili d’istanza particolarmente
self.request: la richiesta (socket) orrendo
self.client_address: guess... il termine
self.server: un’istanza del server
Entro certi limiti, si è indipendenti dal
22. import SocketServer
class EchoHandler(SocketServer.BaseRequestHandler):
def handle(self):
print 'Connected from', self.client_address
try:
for message in self.messages():
if message.upper().startswith('QUIT'):
break
self.request.sendall(message)
finally:
self.request.close()
print 'Disconnected from', self.client_address
def messages(self):
while True:
rec_data = self.request.recv(8192)
if not rec_data: break
yield rec_data
try:
srv = SocketServer.ForkingTCPServer(('', 8881), EchoHandler)
srv.serve_forever()
except KeyboardInterrupt:
print 'Stopping server...'
23. Scriviamo Gumball!
Scriviamo un simulatore di macchine che
distribuiscono palline di gomma
Inserisci un quarto di dollaro
Gira la manovella
Fatti restituire il quarto di dollaro
[consegna la pallina]
L’esempio viene da Head First Design
Patterns, Freeman&Freeman, O’Reilly
24.
25. Il metodo tradizionale
class GumballMachine(object):
SOLD_OUT = 0
NO_QUARTER = 1
HAS_QUARTER = 2
SOLD = 3
def __init__(self, count):
self.count = count
self.state = GumballMachine.SOLD_OUT
if self.count > 0:
self.state = GumballMachine.NO_QUARTER
def insert_quarter(self):
if self.state == GumballMachine.HAS_QUARTER:
print "You can't insert another quarter"
elif self.state == GumballMachine.NO_QUARTER:
self.state = GumballMachine.HAS_QUARTER
print "You inserted a quarter"
elif self.state == GumballMachine.SOLD_OUT:
print "You can't insert a quarter, the machine is sold out"
elif self.state == GumballMachine.SOLD:
print "Please wait, we are already giving you a gumball"
26. Il metodo tradizionale
def eject_quarter(self):
if self.state == GumballMachine.HAS_QUARTER:
print "Quarter returned"
self.state = GumballMachine.NO_QUARTER
elif self.state == GumballMachine.NO_QUARTER:
print "You haven't inserted a quarter"
elif self.state == GumballMachine.SOLD_OUT:
print "You can't eject, you haven't inserted a quarter yet"
elif self.state == GumballMachine.SOLD:
print "Sorry, you already turned the crank"
def turn_crank(self):
if self.state == GumballMachine.SOLD:
print "Turning twice doesn't get you another gumball"
elif self.state == GumballMachine.NO_QUARTER:
print "You turned, but there is no quarter"
elif self.state == GumballMachine.SOLD_OUT:
print "You turned, but there is no quarter"
elif self.state == GumballMachine.HAS_QUARTER:
print "You turned..."
self.state = GumballMachine.SOLD
self.dispense()
27. Il metodo tradizionale
def dispense(self):
if self.state == GumballMachine.SOLD:
print "A gumball comes rolling out of the slot"
self.count -= 1
if self.count == 0:
print "Oops, out of gumballs"
self.state = GumballMachine.SOLD_OUT
else:
self.state = GumballMachine.NO_QUARTER
elif self.state == GumballMachine.NO_QUARTER:
print "You need to pay first"
elif self.state == GumballMachine.SOLD_OUT:
print "No gumball dispensed"
elif self.state == GumballMachine.HAS_QUARTER:
print "No gumball dispensed"
28. Il metodo tradizionale
def dispense(self):
if self.state == GumballMachine.SOLD:
print "A gumball comes rolling out of the slot"
self.count -= 1
if self.count == 0:
print "Oops, out of gumballs"
self.state = GumballMachine.SOLD_OUT
else:
self.state = GumballMachine.NO_QUARTER
elif self.state == GumballMachine.NO_QUARTER:
print "You need to pay first"
elif self.state == GumballMachine.SOLD_OUT:
print "No gumball dispensed"
elif self.state == GumballMachine.HAS_QUARTER:
print "No gumball dispensed"
Ora supponiamo di volere aggiungere uno stato...
31. State pattern e protocolli
Design pattern nei linguaggi dinamici
State pattern
Vediamo il punto di vista per implementare
un protocollo?
32. Pattern state
Gli stati sono rappresentati da oggetti
L’oggetto principale “delega” le azioni ai
metodi degli stati
Eventualmente questi cambiano lo stato
Aggiungere stati diventa facile
33. class GumballMachine(object):
'The true and only gumball machine'
actions = set(['insert_quarter', 'eject_quarter',
'turn_crank', 'dispense'])
def __init__(self, count):
self.no_quarter = NoQuarterState(self)
self.has_quarter = HasQuarterState(self)
self.sold = SoldState(self)
self.sold_out = SoldOutState(self)
self.count = count
self.state = self.sold_out
if self.count > 0:
self.state = self.no_quarter
def __getattr__(self, action):
if action in GumballMachine.actions:
return getattr(self.state, action)
def __str__(self):
return ("nMighty Gumball, Incn"
"Python-enabled Standing Gumball Model #2009n"
"Built from orginal specifications by Freeman&Freeman,"
" Head First Design Patternsn"
"Inventory: %d gumballsn") % (self.count)
34. class HasQuarterState(object):
'Represent a state where the machine has a quarter inside.'
def __init__(self, gumball):
self.gumball = gumball
def insert_quarter(self):
'Perform quarter insertion'
print "You can't insert another quarter"
def eject_quarter(self):
'Ask the quarter back'
print "Quarter returned"
self.gumball.state = self.gumball.no_quarter
def turn_crank(self):
'Turn the crank'
print "You turned..."
self.gumball.state = self.gumball.sold
self.gumball.dispense()
def dispense(self):
'Actually gives the gumball'
print "No gumball dispensed"
35. class NoQuarterState(object):
'Represent a state where the machine has no quarter inside.'
def __init__(self, gumball):
self.gumball = gumball
def insert_quarter(self):
'Perform quarter insertion'
self.gumball.state = self.gumball.has_quarter
print "You inserted a quarter"
def eject_quarter(self):
'Ask the quarter back'
print "You haven't inserted a quarter"
def turn_crank(self):
'Turn the crank'
print "You turned, but there is no quarter"
def dispense(self):
'Actually gives the gumball'
print "You need to pay first"
36. class SoldState(object):
'The machine is to dispense the ball'
def __init__(self, gumball):
self.gumball = gumball
def insert_quarter(self):
'Perform quarter insertion'
print "Please wait, we are already giving you a gumball"
def eject_quarter(self):
'Ask the quarter back'
print "Sorry, you already turned the crank"
def turn_crank(self):
'Turn the crank'
print "Turning twice doesn't get you another gumball"
def dispense(self):
'Actually gives the gumball'
print "A gumball comes rolling out of the slot"
self.gumball.count -= 1
if self.gumball.count == 0:
print "Oops, out of gumballs"
self.gumball.state = self.gumball.sold_out
else:
self.gumball.state = self.gumball.no_quarter
37. class SoldOutState(object):
'No more balls. Sorry guys.'
def __init__(self, gumball):
self.gumball = gumball
def insert_quarter(self):
'Perform quarter insertion'
print "You can't insert a quarter, the machine is sold out"
def eject_quarter(self):
'Ask the quarter back'
print "You can't eject, you haven't inserted a quarter yet"
def turn_crank(self):
'Turn the crank'
print "You turned, but there is no quarter"
def dispense(self):
'Actually gives the gumball'
print "No gumball dispensed"
38. Setattr
def __setattr__(self, name, value): ...
__getattr__viene chiamato solo quando non
si trova l’attributo, __setattr__ è chiamato
sempre
Attenzione ai loop se lo ridefinite!
def __setattr__(self, name, value):
if name in self.names:
self.k = value * self.conversion[name]
elif name == ‘k’:
object.__setattr__(self, name, value)
else:
raise AttributeError, name
41. Web
cgi (sconsigliato)/fastcgi
WSGI: modulo di medio livello per interfacciarsi con i
server
Django: framework completo, molto usato
Nevow: framework completo basato su Twisted
Zope2/3: “mega framework”
Google App Engine (+web.py ev. Django)
web.py: modulo minimalista, facile comprensione
42. Web.py
import web
urls = (
'/(.*)', 'hello'
)
app = web.application(urls, globals())
class hello:
def GET(self, name):
if not name:
name = 'world'
return 'Hello, ' + name + '!'
if __name__ == "__main__":
app.run()
43. XML-RPC Server
from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)
server = SimpleXMLRPCServer(("localhost", 8000),
requestHandler=RequestHandler)
server.register_introspection_functions()
server.register_function(pow)
def adder_function(x,y):
return x + y
server.register_function(adder_function, 'add')
class MyFuncs:
def div(self, x, y):
return x // y
server.register_instance(MyFuncs())
server.serve_forever()
44. XML-RPC Client
import xmlrpclib
s = xmlrpclib.ServerProxy('http://localhost:8000')
print s.pow(2,3) # Returns 2**3 = 8
print s.add(2,3) # Returns 5
print s.div(5,2) # Returns 5//2 = 2
# Print list of available methods
print s.system.listMethods()