SlideShare a Scribd company logo
Интерфейсы
     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

More Related Content

PDF
Types my way: Static Typing in Python
PDF
Writing DSL with Applicative Functors
KEY
Scalaz
PDF
Why you should use super() though it sucks
PDF
Python programming : Abstract classes interfaces
PDF
Introducing Monads and State Monad at PSUG
PDF
Selfish presentation - ruby internals
PDF
Monad Transformers In The Wild
Types my way: Static Typing in Python
Writing DSL with Applicative Functors
Scalaz
Why you should use super() though it sucks
Python programming : Abstract classes interfaces
Introducing Monads and State Monad at PSUG
Selfish presentation - ruby internals
Monad Transformers In The Wild

What's hot (20)

PDF
Functor, Apply, Applicative And Monad
KEY
Scala for ruby programmers
PDF
ppopoff
PPTX
Practical scalaz
PDF
Scala by Luc Duponcheel
PPTX
Monads and friends demystified
PDF
Scalaz 8: A Whole New Game
KEY
Deriving Scalaz
PPTX
Concurrent Application Development using Scala
PDF
Quick swift tour
PDF
Refactoring Functional Type Classes
PPTX
Introduction in php part 2
PDF
Unit test
PDF
The Death of Final Tagless
PDF
Introduction to Swift 2
PDF
First-Class Patterns
PPTX
Introduction in php
PDF
Introduction to ad-3.4, an automatic differentiation library in Haskell
PDF
Scala Intro
PPTX
Managing Input Output Operations
Functor, Apply, Applicative And Monad
Scala for ruby programmers
ppopoff
Practical scalaz
Scala by Luc Duponcheel
Monads and friends demystified
Scalaz 8: A Whole New Game
Deriving Scalaz
Concurrent Application Development using Scala
Quick swift tour
Refactoring Functional Type Classes
Introduction in php part 2
Unit test
The Death of Final Tagless
Introduction to Swift 2
First-Class Patterns
Introduction in php
Introduction to ad-3.4, an automatic differentiation library in Haskell
Scala Intro
Managing Input Output Operations
Ad

Viewers also liked (16)

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

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

PDF
Object Orientation vs Functional Programming in Python
PDF
Introduction to Python
PPTX
Creating Objects in Python
PDF
Python magicmethods
PDF
Type hints Python 3
ODP
PDF
Обзор фреймворка Twisted
PDF
Обзор фреймворка Twisted
PPT
python within 50 page .ppt
PDF
Funkcija, objekt, python
PDF
Scalapeno18 - Thinking Less with Scala
PDF
Intro to Python
KEY
DjangoCon US 2011 - Monkeying around at New Relic
KEY
Djangocon11: Monkeying around at New Relic
PPTX
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
PDF
An overview of Python 2.7
PDF
A tour of Python
PDF
Functions in python
PPTX
Groovy grails types, operators, objects
PDF
Pybelsberg — Constraint-based Programming in Python
Object Orientation vs Functional Programming in Python
Introduction to Python
Creating Objects in Python
Python magicmethods
Type hints Python 3
Обзор фреймворка Twisted
Обзор фреймворка Twisted
python within 50 page .ppt
Funkcija, objekt, python
Scalapeno18 - Thinking Less with Scala
Intro to Python
DjangoCon US 2011 - Monkeying around at New Relic
Djangocon11: Monkeying around at New Relic
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
An overview of Python 2.7
A tour of Python
Functions in python
Groovy grails types, operators, objects
Pybelsberg — Constraint-based Programming in Python

Recently uploaded (20)

PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Approach and Philosophy of On baking technology
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
Programs and apps: productivity, graphics, security and other tools
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PPTX
Big Data Technologies - Introduction.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Spectral efficient network and resource selection model in 5G networks
DOCX
The AUB Centre for AI in Media Proposal.docx
Agricultural_Statistics_at_a_Glance_2022_0.pdf
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Building Integrated photovoltaic BIPV_UPV.pdf
Chapter 3 Spatial Domain Image Processing.pdf
Approach and Philosophy of On baking technology
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
sap open course for s4hana steps from ECC to s4
Reach Out and Touch Someone: Haptics and Empathic Computing
Programs and apps: productivity, graphics, security and other tools
“AI and Expert System Decision Support & Business Intelligence Systems”
MIND Revenue Release Quarter 2 2025 Press Release
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
NewMind AI Weekly Chronicles - August'25-Week II
Big Data Technologies - Introduction.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Unlocking AI with Model Context Protocol (MCP)
Spectral efficient network and resource selection model in 5G networks
The AUB Centre for AI in Media Proposal.docx

Интерфейсы в 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