###### tags: `PYTHON`
# Python
### day-17
#### Create class
1. 建立一個user object以及init model, 後續可以直接使用
2. 假定有個初始值都為0, 可以在init物件時不需要設定param.(例:followers追蹤數一開始都是0)
```
class User:
def __init__(self, user_id, username):
self.id = user_id
self.username = username
self.followers = 0
```
#### add method in class
1. 加入一個計算追蹤數的方法為例
2. 執行方法self為自己, 帶入方法二
```
class User:
def __init__(self, user_id, username):
self.id = user_id
self.username = username
self.followers = 0
self.following = 0
def follow(self, user):
user.followers += 1
self.following += 1
user.followers += 2
```
```
user_1.follow(user_2)
print(user_1.followers)
print(user_1.following)
print(user_2.followers)
print(user_2.following)
```
### 區域變數與全域變數(scope)
suggest: global參數可用大寫撰寫進行區分
1. Local:
```
def zoo():
tiger= 2
printe(tiger)
```
2. Global:
```
tiger= 2
def zoo():
tiger=3
print(tiger)#3
print(tiger) #2
```
### Python dictionaries 新增object in dictionary
1. 新增一個物件:給予一個key, 再利用key值帶入名稱
```
programming_dictionary = {
"Bug": "An error in a program that prevents the program from running as expected.",
"Function": "A piece of code that you can easily call over and over again.",
}
# add new items in a dictionary.
["key"] = "des."
programming_dictionary["Loop"] = "The action of doing something over and over again."
#Edit an item in a dictionary
programming_dictionary["Bug"] = "A moth in your computer."
#Loop through a dictionary
# for key in programming_dictionary:
# print(key)
# print(programming_dictionary[key])
```
### Functions with output
1. 新增一個Function
```
def formate_name(f_name, l_name):
formated_f_name = f_name.title()
formated_l_name = l_name.title()
return f"{formated_f_name} {formated_f_name}"
print(formate_name("askfqSFD", "asSDsDFX"))
```