This commit is contained in:
Pawel Kiczko 2020-05-18 13:22:32 +03:00
parent a2d620aa1a
commit 6e6bceaaf6

View File

@ -25,20 +25,20 @@
- [Creating an Object](#creating-an-object)
- [Class Constructor](#class-constructor)
- [Object Methods](#object-methods)
- [Object default methods](#object-default-methods)
- [Method to modify class default values](#method-to-modify-class-default-values)
- [Object Default Methods](#object-default-methods)
- [Method to Modify Class Default Values](#method-to-modify-class-default-values)
- [Inheritance](#inheritance)
- [Overriding parent method](#overriding-parent-method)
- [Overriding Parent Method](#overriding-parent-method)
- [💻 Exercises: Day 21](#%f0%9f%92%bb-exercises-day-21)
# 📘 Day 21
## Classes and Objects
Python is an object oriented programming language. Everything in Python is an object, with its properties and methods. A number, string, list, dictionary,tuple, set etc. used in a program is an object of a corresponding built-in class. We create class to create an object. A Class is like an object constructor, or a "blueprint" for creating objects. We instantiate a class to create an object. The class defines attributes and the behavior of the object, while the object, on the other hand, represents the class.
Python is an object oriented programming language. Everything in Python is an object, with its properties and methods. A number, string, list, dictionary, tuple, set etc. used in a program is an object of a corresponding built-in class. We create class to create an object. A Class is like an object constructor, or a "blueprint" for creating objects. We instantiate a class to create an object. The class defines attributes and the behavior of the object, while the object, on the other hand, represents the class.
We have been working with classes and objects right from the beginning of these challenge unknowingly. Every element in a Python program is an object of a class.
Let's check if everything in python is class:
We have been working with classes and objects right from the beginning of this challenge unknowingly. Every element in a Python program is an object of a class.
Let's check if everything in python is a class:
```py
Last login: Tue Dec 10 09:35:28 on console
@ -73,7 +73,7 @@ Type "help", "copyright", "credits" or "license" for more information.
### Creating a Class
To create a class we need the key word **class** followed by colon. Class name should be **CamelCase**.
To create a class we need the key word **class** followed by the name and colon. Class name should be **CamelCase**.
```sh
# syntax
@ -103,7 +103,7 @@ print(p)
### Class Constructor
In the above examples, we have created an object from the Person class. However, Class without a constructor is not really useful in real applications. Let's use constructor function to make our class more useful. Like the constructor function in Java or JavaScript, python has also a builtin _**init**()_ constructor function. The _**init**_ constructor function has self parameter which is a reference to the current instance of the class
In the examples above, we have created an object from the Person class. However, Class without a constructor is not really useful in real applications. Let's use constructor function to make our class more useful. Like the constructor function in Java or JavaScript, python has also a built-in _**init**()_ constructor function. The _**init**_ constructor function has self parameter which is a reference to the current instance of the class
**Examples:**
```py
@ -119,9 +119,10 @@ print(p)
```sh
# output
Asabeneh
<__main__.Person object at 0x2abf46907e80>
```
Let's add more parameter to the constructor function.
Let's add more parameters to the constructor function.
```py
class Person:
@ -152,7 +153,8 @@ Helsinki
### Object Methods
Objects can have methods. The methods are functions which are belongs to the object.
Objects can have methods. The methods are functions which belong to the object.
**Example:**
```py
@ -165,7 +167,7 @@ class Person:
self.city = city
def person_info(self):
return f'{self.firstname} {self.lastname} is {self.age} year old. He lives in {self.city}, {self.country}'
return f'{self.firstname} {self.lastname} is {self.age} years old. He lives in {self.city}, {self.country}'
p = Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki')
@ -174,12 +176,12 @@ print(p.person_info())
```sh
# output
Asabeneh Yetayeh is 250 year old. He lives in Helsinki, Finland
Asabeneh Yetayeh is 250 years old. He lives in Helsinki, Finland
```
### Object default methods
### Object Default Methods
Sometimes, you may want to have a default values for you object methods. If we give a default values for the parameters in the constructor, we can avoid error when we call or instantiate our class without parameters. Let's see how it looks using example.
Sometimes, you may want to have a default values for you object methods. If we give default values for the parameters in the constructor, we can avoid errors when we call or instantiate our class without parameters. Let's see how it looks:
**Example:**
@ -193,7 +195,7 @@ class Person:
self.city = city
def person_info(self):
return f'{self.firstname} {self.lastname} is {self.age} year old. He lives in {self.city}, {self.country}.'
return f'{self.firstname} {self.lastname} is {self.age} years old. He lives in {self.city}, {self.country}.'
p1 = Person()
print(p1.person_info())
@ -203,13 +205,13 @@ print(p2.person_info())
```sh
# output
Asabeneh Yetayeh is 250 year old. He lives in Helsinki, Finland.
John Doe is 30 year old. He lives in Noman city, Nomanland.
Asabeneh Yetayeh is 250 years old. He lives in Helsinki, Finland.
John Doe is 30 years old. He lives in Noman city, Nomanland.
```
### Method to modify class default values
### Method to Modify Class Default Values
In the example below, the person class, all the constructor parameters have default values and in addition to that we have a skills default value which we can access it using method. Let's create add_skill method to add skill to the skills list.
In the example below, the person class, all the constructor parameters have default values. In addition to that, we have skills parameter, which we can access using a method. Let's create add_skill method to add skills to the skills list.
```py
class Person:
@ -222,7 +224,7 @@ class Person:
self.skills = []
def person_info(self):
return f'{self.firstname} {self.lastname} is {self.age} year old. He lives in {self.city}, {self.country}.'
return f'{self.firstname} {self.lastname} is {self.age} years old. He lives in {self.city}, {self.country}.'
def add_skill(self, skill):
self.skills.append(skill)
@ -239,16 +241,16 @@ print(p2.skills)
```sh
# output
Asabeneh Yetayeh is 250 year old. He lives in Helsinki, Finland.
John Doe is 30 year old. He lives in Noman city, Nomanland.
Asabeneh Yetayeh is 250 years old. He lives in Helsinki, Finland.
John Doe is 30 years old. He lives in Noman city, Nomanland.
['HTML', 'CSS', 'JavaScript']
[]
```
### Inheritance
Using inheritance we can reuse parent class code. Inheritance allows us to define a class that inherits all the methods and properties from another class. The parent class or super or base class is the class which gives all the methods and properties. Child class is the class the inherits from another class.
Let's see create a student class by inheriting from person class.
Using inheritance we can reuse parent class code. Inheritance allows us to define a class that inherits all the methods and properties from another class. The parent class or super or base class is the class which gives all the methods and properties. Child class is the class that inherits from another class.
Let's create a student class by inheriting from person class.
```py
class Student(Person):
@ -273,14 +275,14 @@ print(s2.skills)
```sh
output
Eyob Yetayeh is 30 year old. He lives in Helsinki, Finland.
Eyob Yetayeh is 30 years old. He lives in Helsinki, Finland.
['JavaScript', 'React', 'Python']
Lidiya Teklemariam is 28 year old. He lives in Espoo, Finland.
Lidiya Teklemariam is 28 years old. He lives in Espoo, Finland.
['Organizing', 'Marketing', 'Digital Marketing']
```
We didn't call the _**init**()_ constructor in the child class. If we didn't call it we can access all the properties but if we call it once we access the parent properties by calling _super_.
We can write add a new method to the child or we can overwrite the parent class by creating the same method name in the child class. When we add the **init**() function, the child class will no longer inherit the parent's **init**() function.
We didn't call the _**init**()_ constructor in the child class. If we didn't call it then we can still access all the properties from the parent. But if we do call the constructor we can access the parent properties by calling _super_.
We can add a new method to the child or we can overwrite the parent class by creating the same method name in the child class. When we add the **init**() function, the child class will no longer inherit the parent's **init**() function.
### Overriding parent method
@ -291,7 +293,7 @@ class Student(Person):
super().__init__(firstname, lastname,age, country, city)
def person_info(self):
gender = 'He' if self.gender =='male' else 'She'
return f'{self.firstname} {self.lastname} is {self.age} year old. {gender} lives in {self.city}, {self.country}.'
return f'{self.firstname} {self.lastname} is {self.age} years old. {gender} lives in {self.city}, {self.country}.'
s1 = Student('Eyob', 'Yetayeh', 30, 'Finland', 'Helsinki','male')
s2 = Student('Lidiya', 'Teklemariam', 28, 'Finland', 'Espoo', 'female')
@ -309,17 +311,17 @@ print(s2.skills)
```
```sh
Eyob Yetayeh is 30 year old. He lives in Helsinki, Finland.
Eyob Yetayeh is 30 years old. He lives in Helsinki, Finland.
['JavaScript', 'React', 'Python']
Lidiya Teklemariam is 28 year old. She lives in Espoo, Finland.
Lidiya Teklemariam is 28 years old. She lives in Espoo, Finland.
['Organizing', 'Marketing', 'Digital Marketing']
```
We can use super() function or the parent name Person to automatically inherit the methods and properties from its parent. In the above example, we override the parant method. The child method has a different feature, it can identify if the gender is male or female and assign the proper pronoun(He/She).
We can use super() function or the parent name Person to automatically inherit the methods and properties from its parent. In the example above we override the parant method. The child method has a different feature, it can identify, if the gender is male or female and assign the proper pronoun(He/She).
## 💻 Exercises: Day 21
1. Python has the module called _statistics_ and we can use this module to do all the statistical caluculations. Hower to challlenge ourselves, let's try to develop a program which calculate measure of central tendency of a sample(mean, median, mode) and measure of variability(range, variance, standard deviation). In addition to those measures find the min, max, count, percentile, and frequency distribution of the sample. You can create a class called Statistics and create all the functions which do statistical calculations as method for the Statistics class. Check the output below.
1. Python has the module called _statistics_ and we can use this module to do all the statistical caluculations. However to challlenge ourselves, let's try to develop a program, which calculates the measure of central tendency of a sample (mean, median, mode) and measure of variability (range, variance, standard deviation). In addition to those measures, find the min, max, count, percentile, and frequency distribution of the sample. You can create a class called Statistics and create all the functions that do statistical calculations as methods for the Statistics class. Check the output below.
```py
ages = [31, 26, 34, 37, 27, 26, 32, 32, 26, 27, 27, 24, 32, 33, 27, 25, 26, 38, 37, 31, 34, 24, 33, 29, 26]
@ -330,12 +332,12 @@ print('Min: ', data.min()) # 24
print('Max: ', data.max()) # 38
print('Range: ', data.range() # 14
print('Mean: ', data.mean()) # 30
print('Median: ',data.median()) # 29
print('Median: ', data.median()) # 29
print('Mode: ', data.mode()) # {'mode': 26, 'count': 5}
print('Variance: ',data.var()) # 17.5
print('Variance: ', data.var()) # 17.5
print('Standard Deviation: ', data.std()) # 4.2
print('Variance: ',data.var()) # 17.5
print('Frequency Distribution: ',data.freq_dist()) # [(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0, 34), (8.0, 33), (8.0, 31), (8.0, 24), (4.0, 38), (4.0, 29), (4.0, 25)]
print('Variance: ', data.var()) # 17.5
print('Frequency Distribution: ', data.freq_dist()) # [(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0, 34), (8.0, 33), (8.0, 31), (8.0, 24), (4.0, 38), (4.0, 29), (4.0, 25)]
```
```sh
@ -354,7 +356,7 @@ Standard Deviation: 4.2
Frequency Distribution: [(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0, 34), (8.0, 33), (8.0, 31), (8.0, 24), (4.0, 38), (4.0, 29), (4.0, 25)]
```
1. Create a class called PersonAccount. It has firstname, lastname, incomes, expenses properties and it has total_income, total_expense, account_info,add_income, add_expense and account_balance methods. Incomes is a set of incomes and its description and the same goes for expenses.
2. Create a class called PersonAccount. It has firstname, lastname, incomes, expenses properties and it has total_income, total_expense, account_info, add_income, add_expense and account_balance methods. Incomes is a set of incomes and its description. The same goes for expenses.
🎉 CONGRATULATIONS ! 🎉