Konstruktor

Konstruktor:

Kod nr 1:

import math


class Point:

    def __init__(self, a, b):
        self.x = a
        self.y = b

    def move(self, mx, my):
        self.x += mx
        self.y += my

    def dist(self, other=None):
        if other is None:
            return math.sqrt(self.x ** 2 + self.y ** 2)
        else:
            return math.sqrt((self.x - other.x) ** 2 + (self.y - other.y) ** 2)


p1 = Point(2, 2)
p1.move(-1, 1)
p2 = Point(3, 4)
print(p1.dist())
print(p1.dist(p2))
print(p1.dist(p1))

Pomieszajmy to trochę:

Kod nr 2:

import math


class Point:
    name = "W"

    def __init__(self, a, b):
        self.x = a
        self.y = b

    def move(self, mx, my):
        self.x += mx
        self.y += my

    def dist(self, other=None):
        if other is None:
            return math.sqrt(self.x ** 2 + self.y ** 2)
        else:
            return math.sqrt((self.x - other.x) ** 2 + (self.y - other.y) ** 2)


p1 = Point(2, 2)
p1.name = "A"
p1.move(-1, 1)
p2 = Point(3, 4)
p3 = Point(2, 0)
p1.name = "R"
Point.name = "T"
p3.name = "g"
Point.name = "v"

Jak opisywać obiekty?

Kod nr 3:

class Person:
    name = "Jan"

    def __str__(self):
        return "Nazwa %s" % (self.name)


p1 = Person()
p1.name="Sylwia"
print(p1)

Kod nr 4:

class Person:

    def __str__(self):
        return type(self).__name__


p1 = Person()
print(p1)

Formatowanie stringów

https://realpython.com/python-string-formatting/#1-old-style-string-formatting-operator

styl printf

Zaczerpnięty z języka C - stare.

https://docs.python.org/3/library/stdtypes.html#old-string-formatting

Kod nr 5:

a = "abc"
str = "a to %s" % a
print(str)
b = 4
c = 5
str2 = "%d + %d = %d" % (b, c, b + c)
print(str2)

styl format

https://realpython.com/python-formatted-output/

Kod nr 6:

a = "abc"
str = "a to {}".format(a)
print(str)
b = 4.2
c = 5
str2 = "{0} + {1} = {2}".format(b, c, b + c)
print(str2)
b = 4.2
c = 5
str2 = "{0:f} + {1:d} = {2:e}".format(b, c, b + c)
print(str2)

f-Strings

https://realpython.com/python-f-strings/#python-f-strings-the-pesky-details

Kod nr 7:

a = "abc"
str = f"a to {a}"
print(str)
b = 4.2
c = 5
str2 = f"{b} + {c} = {b+c}"
print(str2)
b = 4.2
c = 5
str2 = f"{b:f} + {c:d} = {b+c:e}"
print(str2)

Ćwiczenie. Stwórz klasę Godzina i Data w której dodasz metodę __str__ opisującą obiekty w wybranym formacie.

Inaczej?

Kod nr 8:

class Person:
    name = "Jan"

    def __repr__(self):
        return "Nazwa %s" % (self.name)


p1 = Person()
p1.name="Sylwia"
print(p1)

Jakie są różnice?

Kod nr 9:

import datetime

now = datetime.datetime.now()
print(now.__str__())
print(now.__repr__())

Prywatne pola i metody?

Kod nr 10:

class Person:
    __name = "Jan"


p1 = Person()
# print(p1.__name)
print(p1._Person__name)

Ćwiczenie. Dla poniższej klasy sprawdź parę obiektów i sprawdź dostępy do składowych.

Kod nr 11:

class P:
    def __init__(self, name, alias):
        self.name = name  # public
        self.__alias = alias  # private

    def who(self):
        print('name  : ', self.name)
        print('alias : ', self.__alias)

A co z prywatnymi metodami?

Kod nr 12:

class Person:
    __name = "Jan"

    def __get_name(self):
        return self.__name


p1 = Person()
# print(p1.__get_name())
print(p1._Person__get_name())

Ćwiczenie2. Dla poniższej klasy sprawdź parę obiektów i sprawdź dostępy do składowych.

Kod nr 13:

class P:
    def __init__(self, name, alias):
        self.name = name  # public
        self.__alias = alias  # private

    def who(self):
        print('name  : ', self.name)
        print('alias : ', self.__alias)

    def __foo(self):  # private method
        print('This is private method')

    def foo(self):  # public method
        print('This is public method')
        self.__foo()

Operator przypisania

Przeanalizujmy kilka przykładów:

Kod nr 14:

a = 5
b = a
b += 2
print(a)
print(b)

Kod nr 15:

a = True
b = a
b = False
print(a)
print(b)

Kod nr 16:

a = [2, 3, 4]
b = a
print(a)
print(b)
a[1] = -3
print(a)
print(b)
b = [6, 7]
print(a)
print(b)

Dlaczego?

Ćwiczenie Zmodyfikuj kod nr 16 zamiejąc wszystkie listy na krotki (tuple). Co się zmieni?

Co dalej? Przeanalizuj parę kodów:

Kod nr 17:

x = "Olsztyn"
y = "Olsztyn"
print(x == y)
print(x is y)
print(id(x) == id(y))

Kod nr 18:

x = "Olsztyn"
y = x[:: -1][:: -1]
print(x == y)
print(x is y)
print(id(x) == id(y))

Jak to w przypadku obiektów?

Kod nr 19:

class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age


jack1 = Person('Jack', 23)
jack2 = Person('Jack', 23)
print(jack1 == jack2)
print(jack1 is jack2)

Kod nr 20:

class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __eq__(self, other):
        return self.name == other.name and self.age == other.age


jack1 = Person('Jack', 23)
jack2 = Person('Jack', 23)
print(jack1 == jack2)
print(jack1 is jack2)

Ćwiczenie 2. Stwórz klasę Book z kilkoma z kilkoma polami i konstruktorem ustanawiającym pola. Spróbuj na różne sposoby dodać metodę __eq__.

Dziedziczenie

Po co jest dziedziczenie?

Kod nr 21:

class Person:

    def __init__(self, name):
        self.name = name

    def get_name(self):
        return self.name

    def is_employee(self):
        return False


class Employee(Person):

    def is_employee(self):
        return True


emp = Person("Bartek")
print(emp.get_name(), emp.is_employee())

emp = Employee("Sylwia")
print(emp.get_name(), emp.is_employee())

Klasa object jest bazowa dla wszystkich obiektów.

Kod nr 22:

class Person(object):

    def __init__(self, name):
        self.name = name

    def get_name(self):
        return self.name

    def is_employee(self):
        return False


class Employee(Person):

    def is_employee(self):
        return True


emp = Person("Bartek")
print(emp.get_name(), emp.is_employee())

emp = Employee("Sylwia")
print(emp.get_name(), emp.is_employee())

Jak zrobić konstruktor w klasie pochodnej?

Kod nr 23:

class Person:
    def __init__(self, fname, lname):
        self.firstname = fname
        self.lastname = lname

    def printname(self):
        print(self.firstname, self.lastname)


class Student(Person):
    def __init__(self, fname, lname):
        Person.__init__(self, fname, lname)

Kod nr 24:

class Person:
    def __init__(self, fname, lname):
        self.firstname = fname
        self.lastname = lname

    def printname(self):
        print(self.firstname, self.lastname)


class Student(Person):
    def __init__(self, fname, lname):
        super().__init__(fname, lname)

Kod nr 25:

class Person:
    def __init__(self, fname, lname):
        self.firstname = fname
        self.lastname = lname

    def printname(self):
        print(self.firstname, self.lastname)


class Student(Person):
    def __init__(self, fname, lname, year):
        super().__init__(fname, lname)
        self.graduationyear = year

    def welcome(self):
        print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)

Ćwiczenie1. Dodaj do powyższych klas więcej pól i metod i poćwicz ich wywoływanie.