cheatSheet

Last Updated on May 4, 2023 by mishou

Work in progress.

1. Basics 1 Self-taught learning
2. Basics 2 Making your cheat sheets
3. Basics 3 Google Colaboratory
4. Basics 4 Mathematical operators
5. Basics 5 Autofill and List Comprehensions
6. Basics 6 Tables
7. Basics 7 Classes and Objects
8. Basics 8 Pivot Tables
9. Basics 9 Sample Data Sets
10. Basics 10 Flash Fill
11. Basics 11 Charts
12. Basics 12 Loops
13. Basics 13 Funcitons
14. Basics 14 Macros

I. Classes and objects

  • Class: The class is a user-defined data structure that binds the data and methods into a single unit. You can create objects with Class.
  • Object: An object is an instance of a class. It is a collection of attributes and methods.

II. Create a class using the dataclasses module

Dataclasses significantly decrease the amount of boilerplate codes required to write.

Creating class:

from dataclasses import dataclass
@dataclass
class Student:
    name: str
    english: float
    math: float
    group: str
    
    def mean_score(self):
        return (self.english + self.math) / 2

Instantiating objects:

# instantiate objects
joe = Student('Joe', 50, 60, 'A')
betty = Student('Betty', 70, 80, 'A')
jonny = Student('Mishou', 10, 20, 'B')
mary = Student('Mary', 30, 40, 'B')

Let’s calculate the mean of english and math of joe

print(joe.mean_score())

Let’s calculate the mean of english of all students

# create a list of all the Student objects:
students = [joe, betty, jonny, mary]
# calculate the total of all the English scores:
english_total = 0
for student in students:
    english_total += student.english
# calculate the mean of the English scores:
english_mean = english_total / len(students)
print(english_mean)

III. Create classes and objects without using the dataclasses module

# creating class and objects without dataclasses
# create a class
class StudentB:
  def __init__(self, id, english, math, group):
    self.id = id
    self.english = english
    self.math = math
    self.group = group
  def __repr__(self):
    return str((self.id, self.english, self.math, self.group))
  def mean_score(self):
    # calculate the mean of english and math
    return (self.english + self.math)/2
# create a list of objects
students = [StudentB(2, 50, 60, 'A'), StudentB(1, 60, 70, 'A'), StudentB(3, 40, 50, 'B')]
# sort objects by id
print(sorted(students, key=lambda x: x.id))

You can see all the scripts here:

https://colab.research.google.com/drive/1E4gyjQ8Wb683KQf4IEU_qQSGApU6sEI0?usp=sharing

By mishou

Leave a Reply

Your email address will not be published. Required fields are marked *