#100DaysOfCode: Python Day 17

#100DaysOfCode: Python Day 17

The Quiz Project

ยท

2 min read

#100DaysOfCode Day 17

โ“ I CREATED MY OWN TRIVIA GAME! ๐Ÿคจ
CLICK HERE and press "Run" to try it out.
Screenshot 2021-05-28 at 00.24.24.png Screenshot 2021-05-28 at 00.26.14.png

Yesterday I learned how to create my own classes in Python. They are essential in OOP.

Lessons

  1. Stop using Camel Case when writing Python code. Easier said than done as .net loves Camel case!
  2. OOP is awesome if used correctly. Shared domain classes can become so much easier to work with, given they conform to a specific industry.

Case Styles

These are pretty important as every language has its own standards regarding which case style to use when.

  • Pascal Case - HelloWorld
  • Camel Case - helloWorld
  • Snake Case - hello_world

In Python, Pascal and Snake case is used.

Class

An object is simply a collection of data (attributes) and functions (methods) that act on those data. Similarly, a class is a blueprint for that object.

Remember the below image from this medium article. OOP.png

Constructors

A constructor is a part of the class (blueprint) that specifies what should happen when our object is bring constructed/created.
This is also known in programming as initializing an object.

TO THE CODE!!!

# class User:
#    pass

# user_1 = User()
# user_1.id = "001"
# user_1.username = "Rishal"

# print(user_1.username)
# OUTPUT:
# Rishal

######################################

class User:
    # __init__ is a constructor which we can use to define our attributes
    def __init__(self, user_id, username):
        print(f"{username} new user is being created...")
        # These are our attributes
        self.id = user_id
        self.username = username
        self.followers = 0
        self.following = 0

    # This is a method where one user follows another user
    def follow(self, user):
        user.followers += 1
        self.following += 1


# Our two users
user_1 = User("001", "Rishal")
user_2 = User("002", "Elon")

# User 1 follows User 2
user_1.follow(user_2)
print(f"User 1 followers: {user_1.followers}")
print(f"User 1 following: {user_1.following}")
print(f"User 2 followers: {user_2.followers}")
print(f"User 2 following: {user_2.following}")

# OUTPUT:
# Rishal new user is being created...
# Elon new user is being created...
# User 1 followers: 0
# User 1 following: 1
# User 2 followers: 1
# User 2 following: 0

It was another late night learning python, and I am enjoying the peace and quiet while everyone sleeps. I think I will stop fighting my inner night owl and study at night going forward.

Want to stay up to date with my learning journey? Just sign up for my newsletter.