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
-
Naming convention
- https://en.wikipedia.org/wiki/Naming_convention_(programming)
- Class naming rule: PascalCase: 第一字母大寫, 其餘複合字母第一個字母都大寫 (Most programming language)
- Method or Attribute naming rule: camelCase: 第一字母小寫, 其餘複合字母第一個字母都大寫 (like Java )
- Class is a Blueprint that contains attribute and method
- Method or Attribute naming rule: snake_case (like Python, c, c++, Java script)
- Python naming Styles:
補充:
How to Write Beautiful Python Code With PEP 8 - Real Python
-
Class initialize
- to set(variables, counters, switches, etc.) to their starting values at the beginning of a program or subprogram.
- to clear (internal memory, a disk, etc.) of previous data in preparation for use.
-
Working with Attributes : Class Constructions and the __ init __ () function
#initialize attributes
- be invoked every time you create a new object from this class
- def __ init __ (self):
- 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)
- 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