The document discusses various Python concepts including:
1. The Zen of Python principles for writing beautiful, readable code.
2. Types and objects, including how variables are assigned by reference vs value.
3. Reflection capabilities like accessing an object's attributes, methods, and bytecode.
4. Context managers and how the 'with' statement provides a cleaner interface than try/finally blocks.
5. Decorators for modifying functions and methods.
6. List comprehensions and generators for compactly iterating over sequences.
7. Operator overloading for custom number and container types.
8. Class factories including properties, static methods, and inheritance hierarchies.
Pybelsberg is a project allowing constraint-based programming in Python using the Z3 theorem prover [1].
It is available on Github [2] and is licensed under the BSD 3-Clause License.
By Robert Lehmann, Christoph Matthies, Conrad Calmez, Thomas Hille.
See also Babelsberg/R [4] and Babelsberg/JS [5].
[1] https://github.com/Z3Prover/z3
[2] https://github.com/babelsberg/pybelsberg
[3] http://opensource.org/licenses/BSD-3-Clause
[4] https://github.com/timfel/babelsberg-r
[5] https://github.com/timfel/babelsberg-js
Presentation I gave at a Rust Austin meetup in November 2018 about exploring different approaches for interpreting custom DSLs in Rust with varying speed characteristics and associated safety issues.
From java to kotlin beyond alt+shift+cmd+k - Droidcon italyFabio Collini
Kotlin is a first-class language for Android development since Google I/O 2017. And it’s here to stay!
Thanks to Android Studio it’s really easy to introduce Kotlin in an existing project, the configuration is trivial and then we can convert Java classes to Kotlin using a Alt+Shift+Cmd+K. But the new syntax is the just beginning, using Kotlin we can improve our code making it more readable and simpler to write.
In this talk we’ll see how to use some Kotlin features (for example data classes, collections, coroutines and delegates) to simplify Android development comparing the code with the equivalent “modern” Java code. It’s not fair to compare Kotlin code with plain Java 6 code so the Java examples will use lambdas and some external libraries like RxJava and AutoValue.
"Немного о функциональном программирование в JavaScript" Алексей КоваленкоFwdays
Все началось давно, еще в школе, классе эдак 7. Тогда учитель математики впервые произнесла фразу: "Игрек равно эф от икс". В то время я и не догадывался что это самое "эф от икс", является базовым принципом функционального программирования, да и не только функционального.
Functional Programming, Reactive Programming, Transducers, MapReduce и многое другое, так или иначе корнями уходит в то самое, незамысловатое f(x). Это настолько серьезная часть программирования, что ежеминутно, если не ежесекундно, по всему миру на клавиатуре нажимаются клавиши f, u, n, c, t, i, o, n. И нажимаются они именно в этой последовательности.
Пора принять тот факт, что без функционального программирования, программирования не существует!
Пора разобраться. Пора понять для чего нужны функции в программирование, как они должны работать и чем они могут быть полезны в ежедневной работе.
Pybelsberg is a project allowing constraint-based programming in Python using the Z3 theorem prover [1].
It is available on Github [2] and is licensed under the BSD 3-Clause License.
By Robert Lehmann, Christoph Matthies, Conrad Calmez, Thomas Hille.
See also Babelsberg/R [4] and Babelsberg/JS [5].
[1] https://github.com/Z3Prover/z3
[2] https://github.com/babelsberg/pybelsberg
[3] http://opensource.org/licenses/BSD-3-Clause
[4] https://github.com/timfel/babelsberg-r
[5] https://github.com/timfel/babelsberg-js
Presentation I gave at a Rust Austin meetup in November 2018 about exploring different approaches for interpreting custom DSLs in Rust with varying speed characteristics and associated safety issues.
From java to kotlin beyond alt+shift+cmd+k - Droidcon italyFabio Collini
Kotlin is a first-class language for Android development since Google I/O 2017. And it’s here to stay!
Thanks to Android Studio it’s really easy to introduce Kotlin in an existing project, the configuration is trivial and then we can convert Java classes to Kotlin using a Alt+Shift+Cmd+K. But the new syntax is the just beginning, using Kotlin we can improve our code making it more readable and simpler to write.
In this talk we’ll see how to use some Kotlin features (for example data classes, collections, coroutines and delegates) to simplify Android development comparing the code with the equivalent “modern” Java code. It’s not fair to compare Kotlin code with plain Java 6 code so the Java examples will use lambdas and some external libraries like RxJava and AutoValue.
"Немного о функциональном программирование в JavaScript" Алексей КоваленкоFwdays
Все началось давно, еще в школе, классе эдак 7. Тогда учитель математики впервые произнесла фразу: "Игрек равно эф от икс". В то время я и не догадывался что это самое "эф от икс", является базовым принципом функционального программирования, да и не только функционального.
Functional Programming, Reactive Programming, Transducers, MapReduce и многое другое, так или иначе корнями уходит в то самое, незамысловатое f(x). Это настолько серьезная часть программирования, что ежеминутно, если не ежесекундно, по всему миру на клавиатуре нажимаются клавиши f, u, n, c, t, i, o, n. И нажимаются они именно в этой последовательности.
Пора принять тот факт, что без функционального программирования, программирования не существует!
Пора разобраться. Пора понять для чего нужны функции в программирование, как они должны работать и чем они могут быть полезны в ежедневной работе.
This presentation covers how to perform the CRUD operation of database using Django Query-set API. The topics covered includes Creating new objects, Saving changes to existing objects, Retrieving objects from DB, Deleting objects & Complex lookups with Q objects.
It's not news how even some very high profile websites have suffered from serious performance issues owing to large hits on their websites- eventually resulting in monetary loss and above all loss of valuable customers. At Mindfire, with our expert team of Load and Performance testers, we help ensure that streamlined efforts are also being aligned towards this very important aspect of development.
jQuery is so easy to write and therefore so easy to write poor code also. As coders are we sure that what we write can easily be digested by the web page? Lets go and see how we can easily improve performance with same code with different approach.
Slides presenting some numbers of PythonBrasil[8] conference (PyCon Brasil), that happened in Rio de Janeiro, during November 2012. Authors: @tati_alchueyr and @turicas
The HTML5 history API is a standardized way to manipulate the browser history via script.The new parts in HTML5 include a way to add entries to the browser history, to visibly change the URL in the browser location bar (without triggering a page refresh), and an event that fires when those entries are removed from the stack by the user pressing the browser’s back button. This session would help learn more about HTML5 History API.
Django ist ein in Python programmiertes Framework, dass die schnelle Entwicklung von Web-Applikationen ermöglicht. Dabei wird Wert auf sauberen Code und die Wiederverwendbarkeit von einzelnen Komponenten gelegt.
Der Vortrag wurde beim Webmontag Leipzig im März 2010 gehalten.
Python's "batteries included" philosophy means that it comes with an astonishing amount of great stuff. On top of that, there's a vibrant world of third-party libraries that help make Python even more wonderful. We'll go on a breezy, example-filled tour through some of my favorites, from treasures in the standard library to great third-party packages that I don't think I could live without, and we'll touch on some of the fuzzier aspects of the Python culture that make it such a joy to be part of.
ZIO: Powerful and Principled Functional Programming in ScalaWiem Zine Elabidine
This is an introduction of purely functional programming type safe abstractions that provide a variety of features for building asynchronous and concurrent applications data structures built on ZIO.
You'll learn by examples about the power of functional programming to solve the hard problems of software development in a principled, without compromises.
A minimal fluff introduction to Haskell showing enough tools to build a command line application to singularize every word in multiple lines. First presented at the first meeting of the Atlanta Functional Programming Users Group
Slides from my PyCon 2011 talk, "Exhibition of Atrocity," a confessional of my sins against the Python programming language.
Abstract: http://us.pycon.org/2011/schedule/presentations/138/
Video: http://www.pycon.tv/#/video/49
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.
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.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
"Impact of front-end architecture on development cost", Viktor TurskyiFwdays
I have heard many times that architecture is not important for the front-end. Also, many times I have seen how developers implement features on the front-end just following the standard rules for a framework and think that this is enough to successfully launch the project, and then the project fails. How to prevent this and what approach to choose? I have launched dozens of complex projects and during the talk we will analyze which approaches have worked for me and which have not.
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.
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.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
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.
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.
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
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
3. The Zen of Python
○ Beautiful is better than ugly.
○ Explicit is better than implicit.
○ Simple is better than complex.
○ Complex is better than complicated.
○ Flat is better than nested.
○ Sparse is better than dense.
○ Readability counts.
○ Special cases aren't special enough to break the rules.
○ Although practicality beats purity.
○ Errors should never pass silently.
○ Unless explicitly silenced.
○ In the face of ambiguity, refuse the temptation to guess.
○ There should be one -and preferably only one- obvious way to do it.
○ Although that way may not be obvious at first unless you're Dutch.
○ Now is better than never.
○ Although never is often better than right now.
○ If the implementation is hard to explain, it's a bad idea.
○ If the implementation is easy to explain, it may be a good idea.
○ Namespaces are one honking great idea -let's do more of those!
5. Types and objects: To be or not to be
a = 256
b = 256
print (a is b)
a = 257
b = 257
print (a is b)
6. Types and objects: To be or not to be
a = 256
b = 256
print (a is b)
a = 257
b = 257
print (a is b)
True
False
7. Types and objects: To be or not to be
a = 256 a = 256
b = 256 b = 256
print (a is b) print id(a), id(b)
a = 257 a = 257
b = 257 b = 257
print (a is b) print id(a), id(b)
True 22036112 22036112
False 22363568 22363640
8. Types and objects: To be or not to be
a = 256 a = 256
b = 256 b = 256
print (a is b) print id(a), id(b)
a = 257 a = 257
b = 257 b = 257
print (a is b) print id(a), id(b)
True
False
9. Types and objects: To be or not to be
a = 256 a = 256
b = 256 b = 256
print (a is b) print id(a), id(b)
a = 257 a = 257
b = 257 b = 257
print (a is b) print id(a), id(b)
True 22036112 22036112
False 22363568 22363640
10. Types and objects: functions are objects
def x(f):
return f
def y(f):
return x
print x(y)(8)(0)
11. Types and objects: functions are objects
def x(f):
return f
def y(f):
return x
print x(y)(8)(0)
0
12. Types and objects: functions are objects
def x(i):
if x.enabled:
return i
else:
return "disabled"
x.enabled = True
print x(8)
13. Types and objects: functions are objects
def x(i):
if x.enabled:
8
return i
else:
return "disabled"
x.enabled = True
print x(8)
What happened if not set x.enabled?
17. Reflection: get & set
class Example(object):
num = 10
x = Example
dir(x)
hasattr(x, "num") == True
getattr(x, "num", 0) == 10
setattr(x, "num", 20)
18. Reflection: local & global
globals()
Return a dictionary representing the current global symbol table. This is always the dictionary of the
current module (inside a function or method, this is the module where it is defined, not the module from
which it is called).
locals()
Update and return a dictionary representing the current local symbol table. Free
variables are returned by locals() when it is called in function blocks, but not in
class blocks.
19. Reflection: __magic__
__name__
This is the name of the function. This only have a meaningful value is the function is defined with “def”.
__class__
This is a reference to the class a method belongs to.
__code__
This is a reference to the code object used in the implementation of python.
28. Context manager: in the beginning...
item = Item()
try:
item.open()
item.do()
finally:
item.close()
29. Context manager: nowadays...
with Item() as item:
item.do
class Item(object):
def __enter__(self):
self.open()
return self
def __exit__(self,exc_type,exc_value,exc_t):
self.close()
...
30. Context manager: the real world
with file("/tmp/test", "w") as f:
f.write("hello world")
with lock():
# do some concurrent
with sudo("root"):
# do some as root
37. Iterations: comprehesions
squares = []
for x in range(10):
squares.append(x**2)
squares = [x**2 for x in range(10)]
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
{ (k,v) for k,v in [(1,2)] }
38. Iterations: comprehesions
squares = []
for x in range(10):
squares.append(x**2)
squares = [x**2 for x in range(10)]
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
{ (k,v) for k,v in [(1,2)] }
SET NOT DICT!
39. Iterations: comprehesions
squares = []
for x in range(10):
squares.append(x**2)
squares = [x**2 for x in range(10)]
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
{ (k,v) for k,v in [(1,2)] }
SET NOT DICT!
{ k:v for k,v in [(1,2)] }
41. Iterations: co-routine
def countdown(n):
print "Counting down from", n
while n > 0:
yield n
n -= 1
print "Done counting down"
for i in countdown(10):
print i
Counting down from 10
10
9
8
7
6
5
4
3
2
1
Done counting down
42. Iterations: co-routine
def countdown(n):
print "Counting down from", n
while n > 0:
yield n
n -= 1
print "Done counting down"
print countdown(10)
<generator object at 0x4035874c>
50. Overloading: comparison operations
__eq__(self, other) x == y
__lt__(self, other) x<y
__le__(self, other) x <= y
__gt__(self, other) x>y
__ge__(self, other) x >= y
__ne__(self, other) x != y
51. Overloading: containers
__contains__(self, other) y in x
__getitem__(self, other) x[y]
__setitem__(self, other,value) x[y] = z
__delitem__(self, other) del x[y]
__len__(self) len(x)
__reversed__(self) reversed(x)
__iter__(self) iter(x)
53. The Class Factory: class & objects
class Example(object):
attribute = "this is a class attribute"
def __init__(self):
self.attribute = "this is an obj attr override class one"
self.another = "this is another obj attr, no class"
print Example.attribute
print Example().attribute
print Example().another
print Example.another
54. The Class Factory: class & objects
class Example(object):
attribute = "this is a class attribute"
def __init__(self):
self.attribute = "this is an obj attr override class one"
self.another = "this is another obj attr, no class"
print Example.attribute
print Example().attribute
this is a class attribute
print Example().another this is an object attribute and override class one
this is another object attribute, no class
print Example.another
Traceback (most recent call last):
Line 11, in <module>
print Example.another
AttributeError: type object 'Example' has no attribute 'another'
55. The Class Factory: set & get
class Example(object):
def __init__(self):
self._name = x
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value
56. The Class Factory: @property abuse
class Example(object):
def __init__(self, host, port):
self.host = host
self.port = port
@property
def connect(self):
lib.connect(self.host, self.port)
57. The Class Factory: @property abuse
class Example(object):
def __init__(self, host, port):
self.host = host
self.port = port
@property
def connect(self):
lib.connect(self.host, self.port)
NEVER TYPE METHODS AS
PROPERTIES
58. The Class Factory: methods and more methods
@staticmethod
Nothing more than a function defined inside a class.
It is callable without instantiating the class first. It’s
definition is immutable via inheritance.
@classmethod
Also callable without instantiating the class, but its
definition follows Sub class, not Parent class, via
inheritance. That’s because the first argument for
@classmethod function must always be cls (class).
59. The Class Factory: methods and more methods
@staticmethod
Nothing more than a function defined inside a class.
It is callable without instantiating the class first. It’s
definition is immutable via inheritance.
@staticmethod
def static_method():
print "I do not receive nothing :("
@classmethod
Also callable without instantiating the class, but its
definition follows Sub class, not Parent class, via
inheritance. That’s because the first argument for
@classmethod function must always be cls (class).
@classmethod
def class_method(cls):
print "I'm a class %s" % str(cls)
60. The Class Factory: methods and more methods
class Example(object):
def __init__(self, name):
self.name = name
@classmethod
def class_method(cls, name):
return cls(name)
x = Example.class_method("example")
print x
61. The Class Factory: methods and more methods
class Example(object):
def __init__(self, name):
self.name = name
@classmethod
def class_method(cls, name):
return cls(name)
x = Example.class_method("example")
print x
<__main__.Example object at 0x40358b2c>
62. The Class Factory: children and parents
class Example(object):
def __init__(self, name):
self.name = name
def do_something(self):
raise NotImplementedError()
class ChildExample(Example):
def do_something(self):
print self.name
63. The Class Factory: children and parents
class ExampleA(object):
def __init__(self, name):
self.name = name
def do_something(self):
raise NotImplementedError()
class ExampleB(object):
def do_otherthing(self):
raise NotImplementedError()
class ChildExample(ExampleB, ExampleA):
def do_something(self):
print self.name
def do_otherthing(self):
print self.name
64. The Class Factory: τὰ μετὰ τὰ κλάση
class Example(object):
pass
x = Example()
y = Example
print x
print y
65. The Class Factory: τὰ μετὰ τὰ κλάση
class Example(object):
pass
x = Example()
y = Example
print x
print y
<__main__.Example object at 0x4035894c>
<class '__main__.Example'>
66. The Class Factory: τὰ μετὰ τὰ κλάση
def example():
class Example(object):
pass
return Example
x = example()
y = x()
print x
print y
67. The Class Factory: τὰ μετὰ τὰ κλάση
def example():
class Example(object):
pass
return Example
x = example()
y = x()
print x
print y
<class '__main__.Example'>
<__main__.Example object at 0x403589ec>
68. The Class Factory: τὰ μετὰ τὰ κλάση
class Example(object):
pass
print type(Example)
print type(Example())
69. The Class Factory: τὰ μετὰ τὰ κλάση
class Example(object):
pass
print type(Example)
print type(Example())
<type 'type'>
<class '__main__.Example'>
70. The Class Factory: τὰ μετὰ τὰ κλάση
class Example(object):
pass
print type(Example)
print type(Example())
<type 'type'>
<class '__main__.Example'>
71. The Class Factory: τὰ μετὰ τὰ κλάση
class Example(object):
pass
print type(Example)
print type(Example())
<type 'type'>
<class '__main__.Example'>
72. The Class Factory: τὰ μετὰ τὰ κλάση
class Example(object):
pass
x = Example
y = type('Example', (object,), {})
print x
print y
print (x == y)
73. The Class Factory: τὰ μετὰ τὰ κλάση
class Example(object):
pass
x = Example
y = type('Example', (object,), {})
print x
print y
print (x == y)
<class '__main__.Example'>
<class '__main__.Example'>
False
74. The Class Factory: __magic__
__new__(cls, *args, **kwargs)
Is the first method to get called in an object's instantiation, is a
@classmethod, and must return a new instance of type cls.
__init__(self, *args, **kwargs)
Is the initializer for the instance. It gets passed whatever the
primary constructor was called with.
__del__(self)
Is the destructor of the instance, will be invoked before clean
the reference to the instance.
75. The Class Factory: __metaclass__
def upper_attr(f_class_name, f_class_parents, f_class_attr):
attrs = ((name, value)
for name, value in f_class_attr.items()
if not name.startswith('__'))
uppercase_attr = dict((name.upper(), value)
for name, value in attrs)
return type(f_class_name, f_class_parents, uppercase_attr)
class Foo(object):
__metaclass__ = upper_attr
bar = 'bip'
print hasattr(Foo, 'bar')
print hasattr(Foo, 'BAR')
76. The Class Factory: __metaclass__
def upper_attr(f_class_name, f_class_parents, f_class_attr):
attrs = ((name, value)
for name, value in f_class_attr.items()
if not name.startswith('__'))
uppercase_attr = dict((name.upper(), value)
for name, value in attrs)
return type(f_class_name, f_class_parents, uppercase_attr)
class Foo(object):
__metaclass__ = upper_attr
bar = 'bip'
print hasattr(Foo, 'bar') False
print hasattr(Foo, 'BAR') True
87. Documentation: Zen
Don't create documentation for your code.
Code your documentation.
def elements(n):
"""Return a list of n numbers from 0 to n-
1.
"""
return range(0,n)
88. Documentation: everything is an object
def elements(n):
"""Return a list of n numbers from 0 to n-
1.
"""
return range(0,n)
print elements.__doc__
89. Documentation: everything is an object
def elements(n):
"""Return a list of n numbers from 0 to n-
1.
"""
return range(0,n)
print elements.__doc__
Return a list of n numbers from 0 to n-1
90. Documentation: style is important
def elements(n):
"""Return a list of n numbers from 0 to n-1.
:type n: int
:param n: the limit upper for the elements to be created (not
included).
:return: a class:`list` with the items.
"""
return range(0,n)
class Example(object):
"""This is the documentation of the class.
Usually you do not need it :)
"""
def __init__(self, param):
"""This is the documentation of the instance type.
"""