SlideShare uma empresa Scribd logo
1 de 9
Baixar para ler offline
__magické__ metody
    v Pythonu(2.x)




   (ochutnávka)

                     Jirka Vejražka (@JirkaV)
                                @naPyVo #22
class Person(models.Model):
   name = models.CharField(max_length=128)

   def __unicode__(self):
      return self.name

class MojeTrida(object):
   def __init__(self, data):
      self.data = data
>>> mylist = []
>>> dir(mylist)
['__add__', '__class__', '__contains__', '__delattr__',
'__delitem__', '__delslice__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__',
'__getitem__', '__getslice__', '__gt__', '__hash__',
'__iadd__', '__imul__', '__init__',
 '__iter__', '__le__', '__len__', '__lt__', '__mul__',
'__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__reversed__', '__rmul__', '__setattr__',
'__setitem__', '__setslice__', '__sizeof__', '__str__',
'__subclasshook__', 'append', 'count', 'extend',
'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> mystring = 'My hovercraft if full of eels'


>>> if mystring.index('full') > 0:

>>> if ‘full’ in mystring:

object.__contains__(self, item)
Called to implement membership test operators. Should return
true if item is in self, false otherwise. For mapping objects, this
should consider the keys of the mapping rather than the values
or the key-item pairs.
>>> 'full' in 'My hovercraft is full of eels‘
True

>>> class MyStr(str):
...  def __contains__(self, elem):
...     return False

>>> mystring = MyStr('My hovercraft is full of eels')
>>> mystring
'My hovercraft is full of eels'
>>> 'full' in mystring
False
>>> class SortedList(list):
...  def __getitem__(self, key):
...     return sorted(self)[key]

>>> mylist = SortedList([5, 7, 2, 12, 1, 0, 42, 9])
>>> mylist[0]
0
>>> mylist[-1]
42
>>> for x in mylist:
...  print x,
...
5 7 2 12 1 0 42 9
>>> import IPy
>>> class Network(list):
...   def __len__(self):
...      return sum([len(IPy.IP(x)) for x in self])
...
>>> firma = Network(['10.0.10.0/24',
'10.0.20.128/26', '10.0.30.0/25'])

>>> firma
['10.0.10.0/24', '10.0.20.128/26', '10.0.30.0/25']
>>> len(firma)
448
>>> class DobryPrezident(object):
...  def __init__(self, prijmeni):
...     self.prijmeni = prijmeni
...  def __nonzero__(self):
...     return self.prijmeni == 'Cimrman‘

>>> dobry_prezident = DobryPrezident('stara Vomackova')
>>> if dobry_prezident:
...  print 'Mame ji radi!'

>>> dobry_prezident = DobryPrezident('Cimrman')
>>> if dobry_prezident:
...  print 'Budoucnost patri aluminiu!'
...
Budoucnost patri aluminiu!
Dotazy?




Napsáno s použitím fontu Avería (iotic.com/averia/)

Mais conteúdo relacionado

Mais procurados

Symfony2 and Doctrine2 Integration
Symfony2 and Doctrine2 IntegrationSymfony2 and Doctrine2 Integration
Symfony2 and Doctrine2 Integration
Jonathan Wage
 
第二讲 预备-Python基礎
第二讲 预备-Python基礎第二讲 预备-Python基礎
第二讲 预备-Python基礎
anzhong70
 
好みの日本酒を呑みたい! 〜さけのわデータで探す自分好みの酒〜
好みの日本酒を呑みたい! 〜さけのわデータで探す自分好みの酒〜好みの日本酒を呑みたい! 〜さけのわデータで探す自分好みの酒〜
好みの日本酒を呑みたい! 〜さけのわデータで探す自分好みの酒〜
Takashi Kitano
 

Mais procurados (20)

Python Day1
Python Day1Python Day1
Python Day1
 
Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)
 
I regret nothing
I regret nothingI regret nothing
I regret nothing
 
Symfony2 and Doctrine2 Integration
Symfony2 and Doctrine2 IntegrationSymfony2 and Doctrine2 Integration
Symfony2 and Doctrine2 Integration
 
Ecto DSL Introduction - Yurii Bodarev
Ecto DSL Introduction - Yurii BodarevEcto DSL Introduction - Yurii Bodarev
Ecto DSL Introduction - Yurii Bodarev
 
4.1 PHP Arrays
4.1 PHP Arrays4.1 PHP Arrays
4.1 PHP Arrays
 
Python Modules, Packages and Libraries
Python Modules, Packages and LibrariesPython Modules, Packages and Libraries
Python Modules, Packages and Libraries
 
RxSwift 시작하기
RxSwift 시작하기RxSwift 시작하기
RxSwift 시작하기
 
PHP and MySQL
PHP and MySQLPHP and MySQL
PHP and MySQL
 
第二讲 预备-Python基礎
第二讲 预备-Python基礎第二讲 预备-Python基礎
第二讲 预备-Python基礎
 
第二讲 Python基礎
第二讲 Python基礎第二讲 Python基礎
第二讲 Python基礎
 
Intro programacion funcional
Intro programacion funcionalIntro programacion funcional
Intro programacion funcional
 
PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007
 
Python Modules and Libraries
Python Modules and LibrariesPython Modules and Libraries
Python Modules and Libraries
 
Python 표준 라이브러리
Python 표준 라이브러리Python 표준 라이브러리
Python 표준 라이브러리
 
Closure, Higher-order function in Swift
Closure, Higher-order function in SwiftClosure, Higher-order function in Swift
Closure, Higher-order function in Swift
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntity
 
Begin with Python
Begin with PythonBegin with Python
Begin with Python
 
Chap 3php array part1
Chap 3php array part1Chap 3php array part1
Chap 3php array part1
 
好みの日本酒を呑みたい! 〜さけのわデータで探す自分好みの酒〜
好みの日本酒を呑みたい! 〜さけのわデータで探す自分好みの酒〜好みの日本酒を呑みたい! 〜さけのわデータで探す自分好みの酒〜
好みの日本酒を呑みたい! 〜さけのわデータで探す自分好みの酒〜
 

Semelhante a Magicke metody v Pythonu

From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)
Night Sailer
 
Object Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonObject Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in Python
Tendayi Mawushe
 
Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128
PrinceGuru MS
 
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesDesarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Luis Curo Salvatierra
 

Semelhante a Magicke metody v Pythonu (20)

Python 내장 함수
Python 내장 함수Python 내장 함수
Python 내장 함수
 
Python Metaclasses
Python MetaclassesPython Metaclasses
Python Metaclasses
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethods
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)
 
Bottle, o full stack sem Django
Bottle, o full stack sem DjangoBottle, o full stack sem Django
Bottle, o full stack sem Django
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Objective-c Runtime
Objective-c RuntimeObjective-c Runtime
Objective-c Runtime
 
Chapter 2 wbp.pptx
Chapter 2 wbp.pptxChapter 2 wbp.pptx
Chapter 2 wbp.pptx
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیاسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
 
Python_Object_Oriented_Programming.pptx
Python_Object_Oriented_Programming.pptxPython_Object_Oriented_Programming.pptx
Python_Object_Oriented_Programming.pptx
 
WordPress 3.1 at DC PHP
WordPress 3.1 at DC PHPWordPress 3.1 at DC PHP
WordPress 3.1 at DC PHP
 
Object_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdfObject_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdf
 
Dig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoDig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup Cairo
 
Stupid Awesome Python Tricks
Stupid Awesome Python TricksStupid Awesome Python Tricks
Stupid Awesome Python Tricks
 
Groovy collection api
Groovy collection apiGroovy collection api
Groovy collection api
 
Object Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonObject Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in Python
 
Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128
 
Arrays
ArraysArrays
Arrays
 
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesDesarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móviles
 

Último

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 

Magicke metody v Pythonu

  • 1. __magické__ metody v Pythonu(2.x) (ochutnávka) Jirka Vejražka (@JirkaV) @naPyVo #22
  • 2. class Person(models.Model): name = models.CharField(max_length=128) def __unicode__(self): return self.name class MojeTrida(object): def __init__(self, data): self.data = data
  • 3. >>> mylist = [] >>> dir(mylist) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
  • 4. >>> mystring = 'My hovercraft if full of eels' >>> if mystring.index('full') > 0: >>> if ‘full’ in mystring: object.__contains__(self, item) Called to implement membership test operators. Should return true if item is in self, false otherwise. For mapping objects, this should consider the keys of the mapping rather than the values or the key-item pairs.
  • 5. >>> 'full' in 'My hovercraft is full of eels‘ True >>> class MyStr(str): ... def __contains__(self, elem): ... return False >>> mystring = MyStr('My hovercraft is full of eels') >>> mystring 'My hovercraft is full of eels' >>> 'full' in mystring False
  • 6. >>> class SortedList(list): ... def __getitem__(self, key): ... return sorted(self)[key] >>> mylist = SortedList([5, 7, 2, 12, 1, 0, 42, 9]) >>> mylist[0] 0 >>> mylist[-1] 42 >>> for x in mylist: ... print x, ... 5 7 2 12 1 0 42 9
  • 7. >>> import IPy >>> class Network(list): ... def __len__(self): ... return sum([len(IPy.IP(x)) for x in self]) ... >>> firma = Network(['10.0.10.0/24', '10.0.20.128/26', '10.0.30.0/25']) >>> firma ['10.0.10.0/24', '10.0.20.128/26', '10.0.30.0/25'] >>> len(firma) 448
  • 8. >>> class DobryPrezident(object): ... def __init__(self, prijmeni): ... self.prijmeni = prijmeni ... def __nonzero__(self): ... return self.prijmeni == 'Cimrman‘ >>> dobry_prezident = DobryPrezident('stara Vomackova') >>> if dobry_prezident: ... print 'Mame ji radi!' >>> dobry_prezident = DobryPrezident('Cimrman') >>> if dobry_prezident: ... print 'Budoucnost patri aluminiu!' ... Budoucnost patri aluminiu!
  • 9. Dotazy? Napsáno s použitím fontu Avería (iotic.com/averia/)