SlideShare una empresa de Scribd logo
1 de 17
Descargar para leer sin conexión
Интерфейсы
     Andrew Svetlov
andrew.svetlov@gmail.com
  asvetlov.blogspot.com
Интерфейсы
●   Duck Typing
●   ABC
●   Zope Interface
Duck Typing
class A:               >>> a = A()
 def f(self):          >>> b = B();
   print('A.f')        >>> a.f()
class B:               A.f
 def f(self):          >>> b.f()
   print('B.f')        b.f
Pro/Contra
●   Естественная            ●   Неявность
    запись                      интерфейса
●   Ничего лишнего          ●   Сложность само-
●   hasattr vs isinstance       документирования
                            ●   a.x => Point ???
Iterable
●   __iter__             class A:
                          def __getitem__(self, i):
●   __getitem__              if i < 3:
    пока не IndexError         return i
                             raise IndexError("out
                                        of range")
                         >>> a = A()
                         >>> i = iter(a)
                         >>> list(i)
                         [0, 1, 2]
Конструктор dict
●   Аргумент может быть:
●   dict
●   Sequence of 2-elem sequences
●   Mapping??? .keys!!!
●   Iterable
Наследование
class Base:
  def f(self):
   raise NotImplementedError()


class A(Base):
  def f(self):
   return 1
>>> a = A()
>>> isinstance(a, Base)
True
>>> b = Base()   # ???
ABC (Abstract Base Classes)
class Base(abc.Meta):
    @abc.abstractmethod
    def f(self):
       return 0
class A(Base):
    def f(self):
       return super().f() + 1
>>> a = A()
>>> isinstance(a, Base)
True
>>> b = Base()     # ???
Can't instantiate abstract class Base with abstract methods f
>>> a.f()
1
collections.abc
●   Hashable            ●   Mapping
●   Iterable            ●   MutableMapping
●   Iterator            ●   MappingView
●   Sized               ●   KeysView
●   Container
                        ●   ItemsView
●   Callable
●   Set
                        ●   ValuesView
●   MutableSet          ●   Sequence
●   ByteString          ●   MutableSequence
Самодельное множество
from collections import Set   >>> s1 = S({1, 2})
class S(Set):                 >>> 2 in s1
 def __init__(self, s):       True
   super().__init__()
                              >>> s2 = S({2, 3})
   self.s = frozenset(s)
                              >>> s3 = s1|s2
 def __contains__(self, i):
                              >>> list(s3)
   return i in self.s
                              [1, 2, 3]
 def __iter__(self):
   return iter(self.s)        >>> s4 = s1 - s2
 def __len__(self):           >>> list(s4)
   return len(self.s)         [1]
Необязательные методы
●   Наличие метода
●   Проверка на None
●   Исключение NotImplementedError
●   Значение NotImplemented
Наличие метода и None
class A:                       class B(A):
  post = None                   def pre(self):
  def do(self):                        print('B.pre')
   if hasattr(self,
                                def post(self):
                'pre'):
                                       print('B.post')
       self.pre()
   print('A.do')
   if self.post is not None:   >>> b = B()
       self.post()             >>> b.do()
>>> a = A()                    B.pre
>>> a.do()                     A.do
A.do                           B.post
NotImplementedError
class A:                         class B(A):
 def pre(self):                   def pre(self):
   raise NotImplementedError(
                                         print('B.pre')
       'implement pre method')


 def do(self):                   >>> a = A()
   try:                          >>> a.do()
     self.pre()                  A.do
   except NotImplementedError:
                                 >>> b = B()
     pass
   print('A.do')
                                 >>> b.do()
                                 B.pre
                                 a.do
NotImplemented
class A:                    class B:
  def override(self):        def override(self):
    return NotImplemented       return 'overriden'
  def do(self):
                            >>> a = A()
    val = self.override()
                            >>> a.do()
    if (val is not
        NotImplemented):    'default'
     return val             >>> b = B()
    else:                   >>> b.do()
     return 'default'       'overriden'
Zope Interface
class IFile(Interface):
  body = Attribute('Contents of the file.')
class ISize(Interface):
  def getSize():
    'Return the size of an object.'
class File(object):
  implements(IFile)
  body = 'foo bar'
class FileSize(object):
  implements(ISize)
  __used_for__ = IFile
  def __init__(self, context):
    self.context = context
  def getSize(self):
    return len(self.context.body)
Адаптеры
registry = AdapterRegistry()
def hook(provided, obj):
  adapter = registry.lookup1(providedBy(obj),
                             provided, '')
  return adapter(object)
adapter_hooks.append(hook)


>>> file = File()
>>> size = ISize(file)
>>> size.getSize()
Вопросы?
     Andrew Svetlov
andrew.svetlov@gmail.com
  asvetlov.blogspot.com

Más contenido relacionado

La actualidad más candente

Functor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadFunctor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadOliver Daff
 
Scala for ruby programmers
Scala for ruby programmersScala for ruby programmers
Scala for ruby programmerstymon Tobolski
 
Practical scalaz
Practical scalazPractical scalaz
Practical scalazoxbow_lakes
 
Monads and friends demystified
Monads and friends demystifiedMonads and friends demystified
Monads and friends demystifiedAlessandro Lacava
 
Scalaz 8: A Whole New Game
Scalaz 8: A Whole New GameScalaz 8: A Whole New Game
Scalaz 8: A Whole New GameJohn De Goes
 
Deriving Scalaz
Deriving ScalazDeriving Scalaz
Deriving Scalaznkpart
 
Concurrent Application Development using Scala
Concurrent Application Development using ScalaConcurrent Application Development using Scala
Concurrent Application Development using ScalaSiarhiej Siemianchuk
 
Refactoring Functional Type Classes
Refactoring Functional Type ClassesRefactoring Functional Type Classes
Refactoring Functional Type ClassesJohn De Goes
 
The Death of Final Tagless
The Death of Final TaglessThe Death of Final Tagless
The Death of Final TaglessJohn De Goes
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class PatternsJohn De Goes
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskellnebuta
 
Managing Input Output Operations
Managing Input Output OperationsManaging Input Output Operations
Managing Input Output OperationsMunazza-Mah-Jabeen
 

La actualidad más candente (20)

Functor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadFunctor, Apply, Applicative And Monad
Functor, Apply, Applicative And Monad
 
Scala for ruby programmers
Scala for ruby programmersScala for ruby programmers
Scala for ruby programmers
 
ppopoff
ppopoffppopoff
ppopoff
 
Practical scalaz
Practical scalazPractical scalaz
Practical scalaz
 
Scala by Luc Duponcheel
Scala by Luc DuponcheelScala by Luc Duponcheel
Scala by Luc Duponcheel
 
Monads and friends demystified
Monads and friends demystifiedMonads and friends demystified
Monads and friends demystified
 
Scalaz 8: A Whole New Game
Scalaz 8: A Whole New GameScalaz 8: A Whole New Game
Scalaz 8: A Whole New Game
 
Deriving Scalaz
Deriving ScalazDeriving Scalaz
Deriving Scalaz
 
Concurrent Application Development using Scala
Concurrent Application Development using ScalaConcurrent Application Development using Scala
Concurrent Application Development using Scala
 
Quick swift tour
Quick swift tourQuick swift tour
Quick swift tour
 
Refactoring Functional Type Classes
Refactoring Functional Type ClassesRefactoring Functional Type Classes
Refactoring Functional Type Classes
 
Introduction in php part 2
Introduction in php part 2Introduction in php part 2
Introduction in php part 2
 
Unit test
Unit testUnit test
Unit test
 
The Death of Final Tagless
The Death of Final TaglessThe Death of Final Tagless
The Death of Final Tagless
 
Introduction to Swift 2
Introduction to Swift 2Introduction to Swift 2
Introduction to Swift 2
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
 
Introduction in php
Introduction in phpIntroduction in php
Introduction in php
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskell
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
Managing Input Output Operations
Managing Input Output OperationsManaging Input Output Operations
Managing Input Output Operations
 

Destacado

Чем Python плох для стартапа?
Чем Python плох для стартапа?Чем Python плох для стартапа?
Чем Python плох для стартапа?PyNSK
 
Pyton – пробуем функциональный стиль
Pyton – пробуем функциональный стильPyton – пробуем функциональный стиль
Pyton – пробуем функциональный стильPython Meetup
 
Writing Open Source Library
Writing Open Source LibraryWriting Open Source Library
Writing Open Source LibraryAndrew Svetlov
 
Мир Python функционалим с помощью библиотек
Мир Python  функционалим с помощью библиотекМир Python  функционалим с помощью библиотек
Мир Python функционалим с помощью библиотекPyNSK
 
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5PyNSK
 
Получаем текст веб-страниц из Python и как это работает
Получаем текст веб-страниц из Python и как это работаетПолучаем текст веб-страниц из Python и как это работает
Получаем текст веб-страниц из Python и как это работаетPyNSK
 
Python инструменты решения типичных задач
Python  инструменты решения типичных задачPython  инструменты решения типичных задач
Python инструменты решения типичных задачPyNSK
 
Dictionary в Python. По мотивам Objects/dictnotes.txt
Dictionary в Python. По мотивам Objects/dictnotes.txtDictionary в Python. По мотивам Objects/dictnotes.txt
Dictionary в Python. По мотивам Objects/dictnotes.txtPython Meetup
 
Как и зачем можно создать DSL на Python
Как и зачем можно создать DSL на PythonКак и зачем можно создать DSL на Python
Как и зачем можно создать DSL на PythonPyNSK
 
Встреча №9. Будущее паттерна MVVM в iOS приложениях, Денис Лебедев
Встреча №9. Будущее паттерна MVVM в iOS приложениях, Денис ЛебедевВстреча №9. Будущее паттерна MVVM в iOS приложениях, Денис Лебедев
Встреча №9. Будущее паттерна MVVM в iOS приложениях, Денис ЛебедевCocoaHeads
 
Лекция 1. Начало.
Лекция 1. Начало.Лекция 1. Начало.
Лекция 1. Начало.Roman Brovko
 
"Почему язык Lua — это интересно?", Ник Заварицкий, (Mail.ru Group)
"Почему язык Lua — это интересно?", Ник Заварицкий, (Mail.ru Group)"Почему язык Lua — это интересно?", Ник Заварицкий, (Mail.ru Group)
"Почему язык Lua — это интересно?", Ник Заварицкий, (Mail.ru Group)Badoo Development
 
Как создать эффективную презентацию?V 02
Как создать эффективную презентацию?V 02Как создать эффективную презентацию?V 02
Как создать эффективную презентацию?V 02Nadezhda Ivera
 

Destacado (16)

Чем Python плох для стартапа?
Чем Python плох для стартапа?Чем Python плох для стартапа?
Чем Python плох для стартапа?
 
Pyton – пробуем функциональный стиль
Pyton – пробуем функциональный стильPyton – пробуем функциональный стиль
Pyton – пробуем функциональный стиль
 
Import
ImportImport
Import
 
Writing Open Source Library
Writing Open Source LibraryWriting Open Source Library
Writing Open Source Library
 
Py3k
Py3kPy3k
Py3k
 
Мир Python функционалим с помощью библиотек
Мир Python  функционалим с помощью библиотекМир Python  функционалим с помощью библиотек
Мир Python функционалим с помощью библиотек
 
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
 
Получаем текст веб-страниц из Python и как это работает
Получаем текст веб-страниц из Python и как это работаетПолучаем текст веб-страниц из Python и как это работает
Получаем текст веб-страниц из Python и как это работает
 
Python инструменты решения типичных задач
Python  инструменты решения типичных задачPython  инструменты решения типичных задач
Python инструменты решения типичных задач
 
Dictionary в Python. По мотивам Objects/dictnotes.txt
Dictionary в Python. По мотивам Objects/dictnotes.txtDictionary в Python. По мотивам Objects/dictnotes.txt
Dictionary в Python. По мотивам Objects/dictnotes.txt
 
Как и зачем можно создать DSL на Python
Как и зачем можно создать DSL на PythonКак и зачем можно создать DSL на Python
Как и зачем можно создать DSL на Python
 
Встреча №9. Будущее паттерна MVVM в iOS приложениях, Денис Лебедев
Встреча №9. Будущее паттерна MVVM в iOS приложениях, Денис ЛебедевВстреча №9. Будущее паттерна MVVM в iOS приложениях, Денис Лебедев
Встреча №9. Будущее паттерна MVVM в iOS приложениях, Денис Лебедев
 
Asyncio
AsyncioAsyncio
Asyncio
 
Лекция 1. Начало.
Лекция 1. Начало.Лекция 1. Начало.
Лекция 1. Начало.
 
"Почему язык Lua — это интересно?", Ник Заварицкий, (Mail.ru Group)
"Почему язык Lua — это интересно?", Ник Заварицкий, (Mail.ru Group)"Почему язык Lua — это интересно?", Ник Заварицкий, (Mail.ru Group)
"Почему язык Lua — это интересно?", Ник Заварицкий, (Mail.ru Group)
 
Как создать эффективную презентацию?V 02
Как создать эффективную презентацию?V 02Как создать эффективную презентацию?V 02
Как создать эффективную презентацию?V 02
 

Similar a Интерфейсы в Python

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 PythonTendayi Mawushe
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonUC San Diego
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in PythonDamian T. Gordon
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethodsdreampuf
 
Обзор фреймворка Twisted
Обзор фреймворка TwistedОбзор фреймворка Twisted
Обзор фреймворка TwistedPython Meetup
 
Обзор фреймворка Twisted
Обзор фреймворка TwistedОбзор фреймворка Twisted
Обзор фреймворка TwistedMaxim Kulsha
 
python within 50 page .ppt
python within 50 page .pptpython within 50 page .ppt
python within 50 page .pptsushil155005
 
Funkcija, objekt, python
Funkcija, objekt, pythonFunkcija, objekt, python
Funkcija, objekt, pythonRobert Lujo
 
Scalapeno18 - Thinking Less with Scala
Scalapeno18 - Thinking Less with ScalaScalapeno18 - Thinking Less with Scala
Scalapeno18 - Thinking Less with ScalaDaniel Sebban
 
DjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicDjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicGraham Dumpleton
 
Djangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicDjangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicNew Relic
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7decoupled
 
Functions in python
Functions in pythonFunctions in python
Functions in pythonIlian Iliev
 
Groovy grails types, operators, objects
Groovy grails types, operators, objectsGroovy grails types, operators, objects
Groovy grails types, operators, objectsHusain Dalal
 
Pybelsberg — Constraint-based Programming in Python
Pybelsberg — Constraint-based Programming in PythonPybelsberg — Constraint-based Programming in Python
Pybelsberg — Constraint-based Programming in PythonChristoph Matthies
 

Similar a Интерфейсы в Python (20)

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
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in Python
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethods
 
Type hints Python 3
Type hints  Python 3Type hints  Python 3
Type hints Python 3
 
Intro
IntroIntro
Intro
 
Обзор фреймворка Twisted
Обзор фреймворка TwistedОбзор фреймворка Twisted
Обзор фреймворка Twisted
 
Обзор фреймворка Twisted
Обзор фреймворка TwistedОбзор фреймворка Twisted
Обзор фреймворка Twisted
 
python within 50 page .ppt
python within 50 page .pptpython within 50 page .ppt
python within 50 page .ppt
 
Funkcija, objekt, python
Funkcija, objekt, pythonFunkcija, objekt, python
Funkcija, objekt, python
 
Scalapeno18 - Thinking Less with Scala
Scalapeno18 - Thinking Less with ScalaScalapeno18 - Thinking Less with Scala
Scalapeno18 - Thinking Less with Scala
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
DjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicDjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New Relic
 
Djangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicDjangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New Relic
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Groovy grails types, operators, objects
Groovy grails types, operators, objectsGroovy grails types, operators, objects
Groovy grails types, operators, objects
 
Pybelsberg — Constraint-based Programming in Python
Pybelsberg — Constraint-based Programming in PythonPybelsberg — Constraint-based Programming in Python
Pybelsberg — Constraint-based Programming in Python
 

Último

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
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.pptxHampshireHUG
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
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 MountPuma Security, LLC
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
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 Nanonetsnaman860154
 
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 MenDelhi Call girls
 
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 MenDelhi Call girls
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 

Último (20)

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
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
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
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
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
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
 
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
 
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
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 

Интерфейсы в Python

  • 1. Интерфейсы Andrew Svetlov andrew.svetlov@gmail.com asvetlov.blogspot.com
  • 2. Интерфейсы ● Duck Typing ● ABC ● Zope Interface
  • 3. Duck Typing class A: >>> a = A() def f(self): >>> b = B(); print('A.f') >>> a.f() class B: A.f def f(self): >>> b.f() print('B.f') b.f
  • 4. Pro/Contra ● Естественная ● Неявность запись интерфейса ● Ничего лишнего ● Сложность само- ● hasattr vs isinstance документирования ● a.x => Point ???
  • 5. Iterable ● __iter__ class A: def __getitem__(self, i): ● __getitem__ if i < 3: пока не IndexError return i raise IndexError("out of range") >>> a = A() >>> i = iter(a) >>> list(i) [0, 1, 2]
  • 6. Конструктор dict ● Аргумент может быть: ● dict ● Sequence of 2-elem sequences ● Mapping??? .keys!!! ● Iterable
  • 7. Наследование class Base: def f(self): raise NotImplementedError() class A(Base): def f(self): return 1 >>> a = A() >>> isinstance(a, Base) True >>> b = Base() # ???
  • 8. ABC (Abstract Base Classes) class Base(abc.Meta): @abc.abstractmethod def f(self): return 0 class A(Base): def f(self): return super().f() + 1 >>> a = A() >>> isinstance(a, Base) True >>> b = Base() # ??? Can't instantiate abstract class Base with abstract methods f >>> a.f() 1
  • 9. collections.abc ● Hashable ● Mapping ● Iterable ● MutableMapping ● Iterator ● MappingView ● Sized ● KeysView ● Container ● ItemsView ● Callable ● Set ● ValuesView ● MutableSet ● Sequence ● ByteString ● MutableSequence
  • 10. Самодельное множество from collections import Set >>> s1 = S({1, 2}) class S(Set): >>> 2 in s1 def __init__(self, s): True super().__init__() >>> s2 = S({2, 3}) self.s = frozenset(s) >>> s3 = s1|s2 def __contains__(self, i): >>> list(s3) return i in self.s [1, 2, 3] def __iter__(self): return iter(self.s) >>> s4 = s1 - s2 def __len__(self): >>> list(s4) return len(self.s) [1]
  • 11. Необязательные методы ● Наличие метода ● Проверка на None ● Исключение NotImplementedError ● Значение NotImplemented
  • 12. Наличие метода и None class A: class B(A): post = None def pre(self): def do(self): print('B.pre') if hasattr(self, def post(self): 'pre'): print('B.post') self.pre() print('A.do') if self.post is not None: >>> b = B() self.post() >>> b.do() >>> a = A() B.pre >>> a.do() A.do A.do B.post
  • 13. NotImplementedError class A: class B(A): def pre(self): def pre(self): raise NotImplementedError( print('B.pre') 'implement pre method') def do(self): >>> a = A() try: >>> a.do() self.pre() A.do except NotImplementedError: >>> b = B() pass print('A.do') >>> b.do() B.pre a.do
  • 14. NotImplemented class A: class B: def override(self): def override(self): return NotImplemented return 'overriden' def do(self): >>> a = A() val = self.override() >>> a.do() if (val is not NotImplemented): 'default' return val >>> b = B() else: >>> b.do() return 'default' 'overriden'
  • 15. Zope Interface class IFile(Interface): body = Attribute('Contents of the file.') class ISize(Interface): def getSize(): 'Return the size of an object.' class File(object): implements(IFile) body = 'foo bar' class FileSize(object): implements(ISize) __used_for__ = IFile def __init__(self, context): self.context = context def getSize(self): return len(self.context.body)
  • 16. Адаптеры registry = AdapterRegistry() def hook(provided, obj): adapter = registry.lookup1(providedBy(obj), provided, '') return adapter(object) adapter_hooks.append(hook) >>> file = File() >>> size = ISize(file) >>> size.getSize()
  • 17. Вопросы? Andrew Svetlov andrew.svetlov@gmail.com asvetlov.blogspot.com