Intermediate - The Quiz Project & the Benefit of OOP

Goal: what we will make by the end of the day

How to create your own Class in Python

  1. Naming convention

    1. https://en.wikipedia.org/wiki/Naming_convention_(programming)
    2. Class naming rule: PascalCase: 第一字母大寫, 其餘複合字母第一個字母都大寫 (Most programming language)
    3. Method or Attribute naming rule: camelCase: 第一字母小寫, 其餘複合字母第一個字母都大寫 (like Java )
    4. Class is a Blueprint that contains attribute and method
    5. Method or Attribute naming rule: snake_case (like Python, c, c++, Java script)
    6. Python naming Styles:

    補充:

    How to Write Beautiful Python Code With PEP 8 - Real Python

    Untitled

  2. Class initialize

    1. to set(variables, counters, switches, etc.) to their starting values at the beginning of a program or subprogram.
    2. to clear (internal memory, a disk, etc.) of previous data in preparation for use.
  3. Working with Attributes : Class Constructions and the __ init __ () function

    #initialize attributes

    1. be invoked every time you create a new object from this class
    2. def __ init __ (self):
    3. def __ init __(self, attribute):
    class User:
    		def __init__(self,user_id, username):
    				self.id = user_id
    				self.username = username
    				self.follower = 0 #default value
    
    user_1 = User("001", "Brad")
    print(user_1.username)
    
    1. Adding Methods to a Class
class User:
		def __init__(self,user_id, username):
				self.id = user_id
				self.username = username
				self.follower = 0 #default value
				self.following = 0

    def follow(self, user):
				user.followers +=1
				self.following +=1

user_1 = User("001", "Brad")
user_2 = User("002", "Jack")

user_1.follow(user_2)
print(user_1.followers)
print(user_1.following)
print(user_2.followers)
print(user_2.following)

#result:
0
1
1
0

補充: How to Write Beautiful Python Code With PEP 8

How to Write Beautiful Python Code With PEP 8 - Real Python

補充:

[Python物件導向]淺談Python類別(Class)

The Unified Modeling Language User Guide