Programación Orientada A Objetos (OOP)

Transcription

Programación orientada a objetos (OOP)Lic. Rodrigo Lugonesrlugones@df.uba.ar

Struct¿Qué es un struct?Un Struct es una colección de variables. Son accesibles desde unúnico puntero. Internamente están contiguos en memoria.Por ejemplo:struct product {int weight;double price;string name;};product apple;product banana, melon;apple.price 10;2

Google Python Style Guidehttps://goo.gl/kxXVwKhttps://www.pylint.org/3

Programación orientada a objetos OOPen PythonLos objetos son abstracciones de Python para referirse a los datos.Todos los datos en un programa de Python son representados por objetoso por relaciones entre odel.html#4

Workflow procedural1)in2)process3)out5

Workflow en objetos6

Programación orientada a ObjetosClaseUn constructor de objetosEstadoTodas las propiedades de un objetoComportamientoCómo un objeto reacciona frente a una interacción. Esto se lograllamando a ciertos métodos. En OOP es la manera en la que responde aciertos mensajes.IdentidadDistintos objetos pueden tener idénticos estados y el mismocomportamiento, pero cada uno tendrá su identidad.7

8

Programación orientada a smo9

Composición10

Encapsulaciónget obs()decod obs()satelite11

Herencia12

Polimorfismodef decod obs (date, satelites):for satelite in satelites:satelite.decod obs(date)def get obs(date, satelites):for satelite in satelites:satelite.get obs(date)satelites ellite2)satelites.append(satellite3)decod obs (datetime(2016,3,8), satelites)13

Clasesclass TVseries(object):"""Define a tv serie class"""def init (self, name, eps):self.name nameself.eps per s eps# constructor# atributos, variables de clasedef status(self):text '{} has {} episodes per season.'return text.format(self.name, self.eps per s)# método14

Clasesclass TVseries(object):"""Define a tv serie class"""def init (self, name, eps):self.name nameself.eps per s eps# constructor# atributos, variables de clasedef status(self):text '{} has {} episodes per season.'return text.format(self.name, self.eps per s)# métodoIn [26]: got TVseries('Game of Thrones', 10)In [27]: bbt TVseries('Big Bang Theory', 24)In [28]: print bbt.nameBig Bang TheoryIn [31]: print got.nameGame of ThronesIn [32]: print bbt.status()Big Bang Theory has 24 episodes per season.In [33]: print got.status()Game of Thrones has 10 episodes per season.15

Métodosclass TVseries(object):"""Define a tv serie class"""def init (self, name, eps):self.name nameself.eps per s epsself.num watched 0def seen(self, num 1):self.num watched numdef status(self):text '{} has {} episodes per season. I saw {} of them.'return text.format(self.name, self.eps per s, self.num watched)In [26]: got TVseries('Game of Thrones', 10)In [27]: bbt TVseries('Big Bang Theory', 24)In [28]: print bbt.nameBig Bang TheoryIn [31]: bbt.seen(4)In [32]: print bbt.status()Big Bang Theory has 24 episodes per season. I saw 4 of them.In [33]: print got.status()Big Bang Theory has 24 episodes per season. I saw 0 of them.16

Built-in methodsclass TVseries(object):"""Define a tv serie class"""def init (self, name, eps):self.name nameself.eps per s epsdef seen(self, num 1):self.num watched numdef str (self):text '{} has {} episodes per season. I saw {} of them.'return text.format(self.name, self.eps per s , self.num watched )In [26]: got TVseries('Game of Thrones', 10)In [27]: bbt TVseries('Big Bang Theory', 24)In [28]: got.seen(4)In [31]: print gotGame of Thrones has 10 episodes per season. I saw 0 of them.17

Herenciaclass Foo(object):def hello(self):print 'Hello! Foo here.'def bye(self):print 'Bye bye! (implemented in Foo)'class Bar(Foo):def hello(self):print 'Hello! Bar here.'In [2]: f Foo()In [3]: b Bar()In [4]: f.hello()Hello! Foo here.In [5]: f.bye()Bye bye! (implemented in Foo)In [6]: b.hello()Hello! Bar here.In [7]: b.bye()Bye bye! (implemented in Foo)18

Encapsulaciónclass Test(object):def mangled name(self):passdef normal name(self):passIn [3]: mi test Test()In [4]: mi test. mangled ack (most recent call last) ipython-input-4-b2d869da9175 in module ()---- 1 t. mangled name()AttributeError: 'Test' object has no attribute ' mangled name'19

Copiando comportamientoclass Test(object):def init (self):self.val 5 # immutableself.list [5,6,7] # mutableIn [17]: a Test()In [18]: b aIn [19]: c copy(a)In [20]: d deepcopy(a)In [21]: a.val, b.val, c.val, d.valOut[21]: (5, 5, 5, 5)In [22]: a.val 7In [23]: a.val, b.val, c.val, d.valOut[23]: (7, 7, 5, 5)In [24]: a.list, b.list, c.list, d.listOut[24]: ([5, 6, 7], [5, 6, 7], [5, 6, 7], [5, 6, 7])In [25]: a.list.append(999)In [26]: a.list, b.list, c.list, d.listOut[26]: ([5, 6, 7, 999], [5, 6, 7, 999], [5, 6, 7, 999], [5, 6, 7])In [27]: a.list 'Hello'In [28]: a.list, b.listOut[28]: ('Hello', 'Hello', [5, 6, 7, 999], [5, 6, 7])20

sound/init .pyformats/init ead.pyauwrite.py.effects/init .pyecho.pysurround.pyreverse.py.filters/init .pyequalizer.pyvocoder.pykaraoke.pyimport sound.effects as sefrom sound.effects import echofrom sound.effects.echo import echofilter21

Créditos y referenciasModules & ObjectsDavid GrellscheidWorkshop on Advanced Techniques for Scientific Programming and Management of Open Source Software PackagesICPT SAIFRConcepts of Object-Oriented ProgrammingRichard Berger richard.berger@jku.atJohannes Kepler University Linz22

¿Preguntas?23

4 Programación orientada a objetos - OOP en Python Los objetos son abstracciones de Python para referirse a los datos. Todos los datos en un programa de Python son