1
0
Fork 0
Python2017/labs04/Klasy.ipynb

15 KiB
Raw Blame History

Wprowadzenie do Pythona: Klasy

Tomasz Dwojak

3 grudnia 2017

Plan na dziś:

  • klasy,
  • wyjątki.

Python jest językiem obiektowym

  • Wszystko jest obiektem: liczby, napisy, None, funkcje, moduły (biblioteki)...
print((2017).imag)
print(' '.join(['Python', 'da', 'się', 'lubić', '!']))
0
Python da się lubić !

Konstrukcja

class NajprostszaKlasa:
    pass

nasza_klasa = NajprostszaKlasa() # Uwaga na nawiasy na końcu!
print(type(nasza_klasa))
<class '__main__.NajprostszaKlasa'>

(Pseudo) Konstruktor

class Punkt:
    def __init__(self, x, y):
        self.x = x
        self.y = y

punkt = Punkt(2, 3)
print(punkt.x)
2
class Figura:
    def __init__(self, vertexes):
        self.vertexes = vertexes
    
    def liczba_wierzcholkow(self):
        return len(self.vertexes)
    
    def dodaj_wierzcholek(self, x):
        self.vertexes.append(x)
class Prostokat(Figura):
    def __init__(self, vertexes):
        super().__init__(vertexes)
        
    def czy_jestem_kwadratem(self):
        pass
        
class Figura:
    def __init__(self, vertexes):
        self.vertexes = vertexes
    
    def liczba_wierzcholkow(self):
        return len(self.vertexes)
    
    def __len__(self):
        return self.liczba_wierzcholkow()
    
len(Figura([Punkt(2,3), Punkt(3,4), Punkt(0, 0)]))
3

Dobre praktyki: komentarze

class Punkt(object):
    """Klasa reprezentująca punkt w 2D."""
    def __init__(self, x, y):
        """opis argumentów x i y."""
        self.x = x
        self.y = y
help(Punkt)
Help on class Punkt in module __main__:

class Punkt(builtins.object)
 |  Klasa reprezentująca punkt w 2D.
 |  
 |  Methods defined here:
 |  
 |  __init__(self, x, y)
 |      opis argumentów x i y.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)

Enkapsulacja: publiczne czy prywatne?

  • Prywatne zaczynają się od dwóch podkreśleń: __, np. def __policz(self)
  • chronione tylko w konwencji, zaczynają się od '_', np. def _parse(self)
  • publiczne jest wszystko co nie zaczyna się od '_'.
class Parser(object):
    def __parse(self): pass
    def _get(self): pass
parser = Parser()
parser._get()
parser.__parse()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-6-80ee186598d3> in <module>()
      4 parser = Parser()
      5 parser._get()
----> 6 parser.__parse()

AttributeError: 'Parser' object has no attribute '__parse'

Iteratory

class Figura:
    def __init__(self, vertexes):
        self.vertexes = vertexes  
        
    def __iter__(self):
        self.index = -1
        return self
    
    def __next__(self):
        self.index += 1
        if self.index == len(self.vertexes):
            raise StopIteration
        return self.vertexes[self.index]
        
for v in Figura([Punkt(2,3), Punkt(3,4), Punkt(0, 0)]):
    print(v)
<__main__.Punkt object at 0x7f728015b358>
<__main__.Punkt object at 0x7f728015b4a8>
<__main__.Punkt object at 0x7f728015b438>

Atrybuty i metody statyczne

class Klasa:
    atrybut = 0

klasa = Klasa()
print(Klasa.atrybut)
print(klasa.atrybut)
0
0
class Klasa:
    def __init__(self):
        self.t = 0
    def metoda():
        print("Jestem statyczna!")

Klasa.metoda()
Jestem statyczna!

Wyjątki

with open("nieistniejący_plik.txt") as plik:
    content = plik.read()
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-20-41928d542bef> in <module>()
----> 1 with open("nieistniejący_plik.txt") as plik:
      2     print(plik.read())

FileNotFoundError: [Errno 2] No such file or directory: 'nieistniejący_plik.txt'
try:
    with open("nieistniejący_plik.txt") as plik:
        content = plik.read()
except FileNotFoundError:
    contenct = ""
try:
    with open("nieistniejący_plik.txt") as plik:
        content = plik.read()
except FileNotFoundError as e:
    print("Warning {}".format(e))
    contenct = ""
Warning [Errno 2] No such file or directory: 'nieistniejący_plik.txt'
try:
    with open("nieistniejący_plik.txt") as plik:
        content = plik.read()
except Exception as e:
    print("Warning {}".format(e))
    contenct = ""
Warning [Errno 2] No such file or directory: 'nieistniejący_plik.txt'
try:
    with open("nieistniejący_plik.txt") as plik:
        content = plik.read()
except:
    contenct = ""
class Figura:
    def __init__(self, vertexes):
        if len(vertexes) == 0:
            raise Exception("Empty list of vertexes")
        self.vertexes = vertexes
class MyError(Exception):
    def __init__(self, text):
        self.text = text
    def __str__(self):
        return self.text
raise MyError("Coś poszło nie tak!")
---------------------------------------------------------------------------
MyError                                   Traceback (most recent call last)
<ipython-input-36-4fb306b42ebc> in <module>()
----> 1 raise MyError("Coś poszło nie tak!")

MyError: Coś poszło nie tak!