5/16/2020

Python - Working with JSON Data using the json Module

** Working with JSON Data using the json Module


==========================================

''' JavaScript Object Notation '''

import json

people_string = '''
{
"people": [
{
"name": "John Smith",
"phone": "615-555-7164",
"emails": ["johnsmith@bogusemail.com", "john.smith@work-place.com"],
"has_license": false
},
{
"name" : "Jane Doe",
"phone": "560-555-5153",
"emails": null,
"has_license": true
}
  ]
}
'''

data = json.loads(people_string)

print(data)
print()
print(type(data))
print()
print(type(data['people']))

---------------------------------

{'people': [{'name': 'John Smith', 'phone': '615-555-7164', 'emails': ['johnsmith@bogusemail.com', 'john.smith@work-place.com'], 'has_license': False}, {'name': 'Jane Doe', 'phone': '560-555-5153', 'emails': None, 'has_license': True}]}

class 'dict'

class 'list'

---------------------------------

==========================================

https://docs.python.org/3/library/json.html

==========================================

''' JavaScript Object Notation '''

import json

people_string = '''
{
"people": [
{
"name": "John Smith",
"phone": "615-555-7164",
"emails": ["johnsmith@bogusemail.com", "john.smith@work-place.com"],
"has_license": false
},
{
"name" : "Jane Doe",
"phone": "560-555-5153",
"emails": null,
"has_license": true
}
  ]
}
'''

data = json.loads(people_string)

for person in data['people']:
print(person)

---------------------------------

{'name': 'John Smith', 'phone': '615-555-7164', 'emails': ['johnsmith@bogusemail.com', 'john.smith@work-place.com'], 'has_license': False}
{'name': 'Jane Doe', 'phone': '560-555-5153', 'emails': None, 'has_license': True}

---------------------------------

==========================================

''' JavaScript Object Notation '''

import json

people_string = '''
{
"people": [
{
"name": "John Smith",
"phone": "615-555-7164",
"emails": ["johnsmith@bogusemail.com", "john.smith@work-place.com"],
"has_license": false
},
{
"name" : "Jane Doe",
"phone": "560-555-5153",
"emails": null,
"has_license": true
}
  ]
}
'''

data = json.loads(people_string)

for person in data['people']:
print(person['name'])

---------------------------------

John Smith
Jane Doe

---------------------------------

==========================================

''' JavaScript Object Notation '''

import json

people_string = '''
{
"people": [
{
"name": "John Smith",
"phone": "615-555-7164",
"emails": ["johnsmith@bogusemail.com", "john.smith@work-place.com"],
"has_license": false
},
{
"name" : "Jane Doe",
"phone": "560-555-5153",
"emails": null,
"has_license": true
}
  ]
}
'''

data = json.loads(people_string)

for person in data['people']:
del person['phone']

new_string = json.dumps(data)

print(new_string)

---------------------------------

{"people": [{"name": "John Smith", "emails": ["johnsmith@bogusemail.com", "john.smith@work-place.com"], "has_license": false}, {"name": "Jane Doe", "emails": null, "has_license": true}]}

---------------------------------


==========================================

''' JavaScript Object Notation '''

import json

people_string = '''
{
"people": [
{
"name": "John Smith",
"phone": "615-555-7164",
"emails": ["johnsmith@bogusemail.com", "john.smith@work-place.com"],
"has_license": false
},
{
"name" : "Jane Doe",
"phone": "560-555-5153",
"emails": null,
"has_license": true
}
  ]
}
'''

data = json.loads(people_string)

for person in data['people']:
del person['phone']

new_string = json.dumps(data, indent = 2)

print(new_string)

---------------------------------

{
  "people": [
    {
      "name": "John Smith",
      "emails": [
        "johnsmith@bogusemail.com",
        "john.smith@work-place.com"
      ],
      "has_license": false
    },
    {
      "name": "Jane Doe",
      "emails": null,
      "has_license": true
    }
  ]
}

---------------------------------

==========================================

''' JavaScript Object Notation '''

import json

people_string = '''
{
"people": [
{
"name": "John Smith",
"phone": "615-555-7164",
"emails": ["johnsmith@bogusemail.com", "john.smith@work-place.com"],
"has_license": false
},
{
"name" : "Jane Doe",
"phone": "560-555-5153",
"emails": null,
"has_license": true
}
  ]
}
'''

data = json.loads(people_string)

for person in data['people']:
del person['phone']

new_string = json.dumps(data, indent = 2, sort_keys = True)

print(new_string)


---------------------------------

{
  "people": [
    {
      "emails": [
        "johnsmith@bogusemail.com",
        "john.smith@work-place.com"
      ],
      "has_license": false,
      "name": "John Smith"
    },
    {
      "emails": null,
      "has_license": true,
      "name": "Jane Doe"
    }
  ]
}

---------------------------------

==========================================

''' JavaScript Object Notation '''

import json

with open('states.json') as f:
data = json.load(f)

for state in data['states']:
print(state)


---------------------------------

{'name': 'Alabama', 'abbreviation': 'AL', 'area_codes': ['205', '251', '256', '334', '938']}
{'name': 'Alaska', 'abbreviation': 'AK', 'area_codes': ['907']}
{'name': 'Arizona', 'abbreviation': 'AZ', 'area_codes': ['480', '520', '602', '623', '928']}
{'name': 'Arkansas', 'abbreviation': 'AR', 'area_codes': ['479', '501', '870']}
{'name': 'California', 'abbreviation': 'CA', 'area_codes': ['209', '213', '310', '323', '408', '415', '424', '442', '510', '530', '559', '562', '619', '626', '628', '650', '657', '661', '669', '707', '714', '747', '760', '805', '818', '831', '858', '909', '916', '925', '949', '951']}
{'name': 'Colorado', 'abbreviation': 'CO', 'area_codes': ['303', '719', '720', '970']}
{'name': 'Connecticut', 'abbreviation': 'CT', 'area_codes': ['203', '475', '860', '959']}
{'name': 'Delaware', 'abbreviation': 'DE', 'area_codes': ['302']}
{'name': 'Florida', 'abbreviation': 'FL', 'area_codes': ['239', '305', '321', '352', '386', '407', '561', '727', '754', '772', '786', '813', '850', '863', '904', '941', '954']}
{'name': 'Georgia', 'abbreviation': 'GA', 'area_codes': ['229', '404', '470', '478', '678', '706', '762', '770', '912']}
{'name': 'Hawaii', 'abbreviation': 'HI', 'area_codes': ['808']}
{'name': 'Idaho', 'abbreviation': 'ID', 'area_codes': ['208']}
{'name': 'Illinois', 'abbreviation': 'IL', 'area_codes': ['217', '224', '309', '312', '331', '618', '630', '708', '773', '779', '815', '847', '872']}
{'name': 'Indiana', 'abbreviation': 'IN', 'area_codes': ['219', '260', '317', '463', '574', '765', '812', '930']}
{'name': 'Iowa', 'abbreviation': 'IA', 'area_codes': ['319', '515', '563', '641', '712']}
{'name': 'Kansas', 'abbreviation': 'KS', 'area_codes': ['316', '620', '785', '913']}
{'name': 'Kentucky', 'abbreviation': 'KY', 'area_codes': ['270', '364', '502', '606', '859']}
{'name': 'Louisiana', 'abbreviation': 'LA', 'area_codes': ['225', '318', '337', '504', '985']}
{'name': 'Maine', 'abbreviation': 'ME', 'area_codes': ['207']}
{'name': 'Maryland', 'abbreviation': 'MD', 'area_codes': ['240', '301', '410', '443', '667']}
{'name': 'Massachusetts', 'abbreviation': 'MA', 'area_codes': ['339', '351', '413', '508', '617', '774', '781', '857', '978']}
{'name': 'Michigan', 'abbreviation': 'MI', 'area_codes': ['231', '248', '269', '313', '517', '586', '616', '734', '810', '906', '947', '989']}
{'name': 'Minnesota', 'abbreviation': 'MN', 'area_codes': ['218', '320', '507', '612', '651', '763', '952']}
{'name': 'Mississippi', 'abbreviation': 'MS', 'area_codes': ['228', '601', '662', '769']}
{'name': 'Missouri', 'abbreviation': 'MO', 'area_codes': ['314', '417', '573', '636', '660', '816']}
{'name': 'Montana', 'abbreviation': 'MT', 'area_codes': ['406']}
{'name': 'Nebraska', 'abbreviation': 'NE', 'area_codes': ['308', '402', '531']}
{'name': 'Nevada', 'abbreviation': 'NV', 'area_codes': ['702', '725', '775']}
{'name': 'New Hampshire', 'abbreviation': 'NH', 'area_codes': ['603']}
{'name': 'New Jersey', 'abbreviation': 'NJ', 'area_codes': ['201', '551', '609', '732', '848', '856', '862', '908', '973']}
{'name': 'New Mexico', 'abbreviation': 'NM', 'area_codes': ['505', '575']}
{'name': 'New York', 'abbreviation': 'NY', 'area_codes': ['212', '315', '332', '347', '516', '518', '585', '607', '631', '646', '680', '716', '718', '845', '914', '917', '929', '934']}
{'name': 'North Carolina', 'abbreviation': 'NC', 'area_codes': ['252', '336', '704', '743', '828', '910', '919', '980', '984']}
{'name': 'North Dakota', 'abbreviation': 'ND', 'area_codes': ['701']}
{'name': 'Ohio', 'abbreviation': 'OH', 'area_codes': ['216', '220', '234', '330', '380', '419', '440', '513', '567', '614', '740', '937']}
{'name': 'Oklahoma', 'abbreviation': 'OK', 'area_codes': ['405', '539', '580', '918']}
{'name': 'Oregon', 'abbreviation': 'OR', 'area_codes': ['458', '503', '541', '971']}
{'name': 'Pennsylvania', 'abbreviation': 'PA', 'area_codes': ['215', '267', '272', '412', '484', '570', '610', '717', '724', '814', '878']}
{'name': 'Rhode Island', 'abbreviation': 'RI', 'area_codes': ['401']}
{'name': 'South Carolina', 'abbreviation': 'SC', 'area_codes': ['803', '843', '854', '864']}
{'name': 'South Dakota', 'abbreviation': 'SD', 'area_codes': ['605']}
{'name': 'Tennessee', 'abbreviation': 'TN', 'area_codes': ['423', '615', '629', '731', '865', '901', '931']}
{'name': 'Texas', 'abbreviation': 'TX', 'area_codes': ['210', '214', '254', '281', '325', '346', '361', '409', '430', '432', '469', '512', '682', '713', '737', '806', '817', '830', '832', '903', '915', '936', '940', '956', '972', '979']}
{'name': 'Utah', 'abbreviation': 'UT', 'area_codes': ['385', '435', '801']}
{'name': 'Vermont', 'abbreviation': 'VT', 'area_codes': ['802']}
{'name': 'Virginia', 'abbreviation': 'VA', 'area_codes': ['276', '434', '540', '571', '703', '757', '804']}
{'name': 'Washington', 'abbreviation': 'WA', 'area_codes': ['206', '253', '360', '425', '509']}
{'name': 'West Virginia', 'abbreviation': 'WV', 'area_codes': ['304', '681']}
{'name': 'Wisconsin', 'abbreviation': 'WI', 'area_codes': ['262', '414', '534', '608', '715', '920']}
{'name': 'Wyoming', 'abbreviation': 'WY', 'area_codes': ['307']}

---------------------------------

==========================================

''' JavaScript Object Notation '''

import json

with open('states.json') as f:
data = json.load(f)

for state in data['states']:
print(state['name'], state['abbreviation'])

---------------------------------

Alabama AL
Alaska AK
Arizona AZ
Arkansas AR
California CA
Colorado CO
Connecticut CT
Delaware DE
Florida FL
Georgia GA
Hawaii HI
Idaho ID
Illinois IL
Indiana IN
Iowa IA
Kansas KS
Kentucky KY
Louisiana LA
Maine ME
Maryland MD
Massachusetts MA
Michigan MI
Minnesota MN
Mississippi MS
Missouri MO
Montana MT
Nebraska NE
Nevada NV
New Hampshire NH
New Jersey NJ
New Mexico NM
New York NY
North Carolina NC
North Dakota ND
Ohio OH
Oklahoma OK
Oregon OR
Pennsylvania PA
Rhode Island RI
South Carolina SC
South Dakota SD
Tennessee TN
Texas TX
Utah UT
Vermont VT
Virginia VA
Washington WA
West Virginia WV
Wisconsin WI
Wyoming WY

---------------------------------

==========================================

''' JavaScript Object Notation '''

import json

with open('states.json') as f:
data = json.load(f)

for state in data['states']:
del state['area_codes']

with open('new_states.json', 'w') as f:
json.dump(data, f)

---------------------------------

{"states": [{"name": "Alabama", "abbreviation": "AL"}, {"name": "Alaska", "abbreviation": "AK"}, {"name": "Arizona", "abbreviation": "AZ"}, {"name": "Arkansas", "abbreviation": "AR"}, {"name": "California", "abbreviation": "CA"}, {"name": "Colorado", "abbreviation": "CO"}, {"name": "Connecticut", "abbreviation": "CT"}, {"name": "Delaware", "abbreviation": "DE"}, {"name": "Florida", "abbreviation": "FL"}, {"name": "Georgia", "abbreviation": "GA"}, {"name": "Hawaii", "abbreviation": "HI"}, {"name": "Idaho", "abbreviation": "ID"}, {"name": "Illinois", "abbreviation": "IL"}, {"name": "Indiana", "abbreviation": "IN"}, {"name": "Iowa", "abbreviation": "IA"}, {"name": "Kansas", "abbreviation": "KS"}, {"name": "Kentucky", "abbreviation": "KY"}, {"name": "Louisiana", "abbreviation": "LA"}, {"name": "Maine", "abbreviation": "ME"}, {"name": "Maryland", "abbreviation": "MD"}, {"name": "Massachusetts", "abbreviation": "MA"}, {"name": "Michigan", "abbreviation": "MI"}, {"name": "Minnesota", "abbreviation": "MN"}, {"name": "Mississippi", "abbreviation": "MS"}, {"name": "Missouri", "abbreviation": "MO"}, {"name": "Montana", "abbreviation": "MT"}, {"name": "Nebraska", "abbreviation": "NE"}, {"name": "Nevada", "abbreviation": "NV"}, {"name": "New Hampshire", "abbreviation": "NH"}, {"name": "New Jersey", "abbreviation": "NJ"}, {"name": "New Mexico", "abbreviation": "NM"}, {"name": "New York", "abbreviation": "NY"}, {"name": "North Carolina", "abbreviation": "NC"}, {"name": "North Dakota", "abbreviation": "ND"}, {"name": "Ohio", "abbreviation": "OH"}, {"name": "Oklahoma", "abbreviation": "OK"}, {"name": "Oregon", "abbreviation": "OR"}, {"name": "Pennsylvania", "abbreviation": "PA"}, {"name": "Rhode Island", "abbreviation": "RI"}, {"name": "South Carolina", "abbreviation": "SC"}, {"name": "South Dakota", "abbreviation": "SD"}, {"name": "Tennessee", "abbreviation": "TN"}, {"name": "Texas", "abbreviation": "TX"}, {"name": "Utah", "abbreviation": "UT"}, {"name": "Vermont", "abbreviation": "VT"}, {"name": "Virginia", "abbreviation": "VA"}, {"name": "Washington", "abbreviation": "WA"}, {"name": "West Virginia", "abbreviation": "WV"}, {"name": "Wisconsin", "abbreviation": "WI"}, {"name": "Wyoming", "abbreviation": "WY"}]}

---------------------------------

==========================================

''' JavaScript Object Notation '''

import json

with open('states.json') as f:
data = json.load(f)

for state in data['states']:
del state['area_codes']

with open('new_states.json', 'w') as f:
json.dump(data, f, indent = 2)

---------------------------------

{
  "states": [
    {
      "name": "Alabama",
      "abbreviation": "AL"
    },
    {
      "name": "Alaska",
      "abbreviation": "AK"
    },
    {
      "name": "Arizona",
      "abbreviation": "AZ"
    },
    {
      "name": "Arkansas",
      "abbreviation": "AR"
    },
    {
      "name": "California",
      "abbreviation": "CA"
    },
    {
      "name": "Colorado",
      "abbreviation": "CO"
    },
    {
      "name": "Connecticut",
      "abbreviation": "CT"
    },
    {
      "name": "Delaware",
      "abbreviation": "DE"
    },
    {
      "name": "Florida",
      "abbreviation": "FL"
    },
    {
      "name": "Georgia",
      "abbreviation": "GA"
    },
    {
      "name": "Hawaii",
      "abbreviation": "HI"
    },
    {
      "name": "Idaho",
      "abbreviation": "ID"
    },
    {
      "name": "Illinois",
      "abbreviation": "IL"
    },
    {
      "name": "Indiana",
      "abbreviation": "IN"
    },
    {
      "name": "Iowa",
      "abbreviation": "IA"
    },
    {
      "name": "Kansas",
      "abbreviation": "KS"
    },
    {
      "name": "Kentucky",
      "abbreviation": "KY"
    },
    {
      "name": "Louisiana",
      "abbreviation": "LA"
    },
    {
      "name": "Maine",
      "abbreviation": "ME"
    },
    {
      "name": "Maryland",
      "abbreviation": "MD"
    },
    {
      "name": "Massachusetts",
      "abbreviation": "MA"
    },
    {
      "name": "Michigan",
      "abbreviation": "MI"
    },
    {
      "name": "Minnesota",
      "abbreviation": "MN"
    },
    {
      "name": "Mississippi",
      "abbreviation": "MS"
    },
    {
      "name": "Missouri",
      "abbreviation": "MO"
    },
    {
      "name": "Montana",
      "abbreviation": "MT"
    },
    {
      "name": "Nebraska",
      "abbreviation": "NE"
    },
    {
      "name": "Nevada",
      "abbreviation": "NV"
    },
    {
      "name": "New Hampshire",
      "abbreviation": "NH"
    },
    {
      "name": "New Jersey",
      "abbreviation": "NJ"
    },
    {
      "name": "New Mexico",
      "abbreviation": "NM"
    },
    {
      "name": "New York",
      "abbreviation": "NY"
    },
    {
      "name": "North Carolina",
      "abbreviation": "NC"
    },
    {
      "name": "North Dakota",
      "abbreviation": "ND"
    },
    {
      "name": "Ohio",
      "abbreviation": "OH"
    },
    {
      "name": "Oklahoma",
      "abbreviation": "OK"
    },
    {
      "name": "Oregon",
      "abbreviation": "OR"
    },
    {
      "name": "Pennsylvania",
      "abbreviation": "PA"
    },
    {
      "name": "Rhode Island",
      "abbreviation": "RI"
    },
    {
      "name": "South Carolina",
      "abbreviation": "SC"
    },
    {
      "name": "South Dakota",
      "abbreviation": "SD"
    },
    {
      "name": "Tennessee",
      "abbreviation": "TN"
    },
    {
      "name": "Texas",
      "abbreviation": "TX"
    },
    {
      "name": "Utah",
      "abbreviation": "UT"
    },
    {
      "name": "Vermont",
      "abbreviation": "VT"
    },
    {
      "name": "Virginia",
      "abbreviation": "VA"
    },
    {
      "name": "Washington",
      "abbreviation": "WA"
    },
    {
      "name": "West Virginia",
      "abbreviation": "WV"
    },
    {
      "name": "Wisconsin",
      "abbreviation": "WI"
    },
    {
      "name": "Wyoming",
      "abbreviation": "WY"
    }
  ]
}

---------------------------------

==========================================

import json
from urllib.request import urlopen

with urlopen("https://finance.yahoo.com/?format=json") as response:
source = response.read()

print(source)

data = json.loads(source)

print(json.dumps(data, indent=2))

---------------------------------




---------------------------------

==========================================

import json
from urllib.request import urlopen

with urlopen("https://finance.yahoo.com/?format=json") as response:
source = response.read()

print(source)

data = json.loads(source)


print(len(data['list']['resources']))

---------------------------------

차후 연구

---------------------------------

==========================================

import json
from urllib.request import urlopen

with urlopen("https://finance.yahoo.com/?format=json") as response:
source = response.read()

print(source)

data = json.loads(source)

for item in data['list']['resources']:
print(item)

-------------차후 연구----------




---------------------------------

==========================================


import json
from urllib.request import urlopen

with urlopen("https://finance.yahoo.com/?format=json") as response:
source = response.read()

print(source)

data = json.loads(source)

for item in data['list']['resources']:
name = item['resources']['fields']['name']
price = item['resources']['fields']['price']
print(name, price)

-------------차후 연구----------




---------------------------------

==========================================

import json
from urllib.request import urlopen

with urlopen("https://finance.yahoo.com/?format=json") as response:
source = response.read()

print(source)

data = json.loads(source)

usd_rates = dict()

for item in data['list']['resources']:
name = item['resources']['fields']['name']
price = item['resources']['fields']['price']
usd_rates[name] = price

print(usd_rates['USD/EUR'])

---------------------------------

0.846500 <~~ 변동 가능

---------------------------------

==========================================

import json
from urllib.request import urlopen

with urlopen("https://finance.yahoo.com/?format=json") as response:
source = response.read()

print(source)

data = json.loads(source)

usd_rates = dict()

for item in data['list']['resources']:
name = item['resources']['fields']['name']
price = item['resources']['fields']['price']
usd_rates[name] = price

print(50 * float(usd_rates['USD/EUR']))
print(50 * float(usd_rates['USD/INR']))

---------------------------------

42.325 <~~ 변동 가능

3240.2500000000005 <~~ 변동 가능

---------------------------------


Python - Web Scraping with BeautifulSoup and Requests

** Web Scraping with BeautifulSoup and Requests


==========================================

C:\Users\purunet>pip install beautifulsoup4
Collecting beautifulsoup4
  Downloading beautifulsoup4-4.9.0-py3-none-any.whl (109 kB)
     |████████████████████████████████| 109 kB 8.9 kB/s
Collecting soupsieve>1.2
  Downloading soupsieve-2.0-py2.py3-none-any.whl (32 kB)
Installing collected packages: soupsieve, beautifulsoup4
Successfully installed beautifulsoup4-4.9.0 soupsieve-2.0

==========================================

C:\Users\purunet>pip install lxml
Collecting lxml
  Downloading lxml-4.5.0-cp38-cp38-win32.whl (3.3 MB)
     |████████████████████████████████| 3.3 MB 1.3 MB/s
Installing collected packages: lxml
Successfully installed lxml-4.5.0

==========================================

C:\Users\purunet>pip install html5lib
Collecting html5lib
  Downloading html5lib-1.0.1-py2.py3-none-any.whl (117 kB)
     |████████████████████████████████| 117 kB 233 kB/s
Collecting webencodings
  Downloading webencodings-0.5.1-py2.py3-none-any.whl (11 kB)
Requirement already satisfied: six>=1.9 in c:\users\purunet\appdata\roaming\pyth
on\python38\site-packages (from html5lib) (1.14.0)
Installing collected packages: webencodings, html5lib
Successfully installed html5lib-1.0.1 webencodings-0.5.1

==========================================

C:\Users\purunet>pip install requests
Collecting requests
  Downloading requests-2.23.0-py2.py3-none-any.whl (58 kB)
     |████████████████████████████████| 58 kB 153 kB/s
Collecting idna<3>=2.5
  Downloading idna-2.9-py2.py3-none-any.whl (58 kB)
     |████████████████████████████████| 58 kB 454 kB/s
Collecting certifi>=2017.4.17
  Downloading certifi-2020.4.5.1-py2.py3-none-any.whl (157 kB)
     |████████████████████████████████| 157 kB 547 kB/s
Collecting urllib3!=1.25.0,!=1.25.1,<1 .26="">=1.21.1
  Downloading urllib3-1.25.9-py2.py3-none-any.whl (126 kB)
     |████████████████████████████████| 126 kB 2.2 MB/s
Collecting chardet<4>=3.0.2
  Downloading chardet-3.0.4-py2.py3-none-any.whl (133 kB)
     |████████████████████████████████| 133 kB 3.3 MB/s
Installing collected packages: idna, certifi, urllib3, chardet, requests
Successfully installed certifi-2020.4.5.1 chardet-3.0.4 idna-2.9 requests-2.23.0
 urllib3-1.25.9

==========================================

from bs4 import BeautifulSoup

import requests

with open('simple.html') as html_file:
soup = BeautifulSoup(html_file, 'lxml')

print(soup)

---------------------------------




---------------------------------

==========================================

from bs4 import BeautifulSoup

import requests

with open('simple.html') as html_file:
soup = BeautifulSoup(html_file, 'lxml')

print(soup.prettify())

---------------------------------




---------------------------------


==========================================

from bs4 import BeautifulSoup

import requests

with open('simple.html') as html_file:
soup = BeautifulSoup(html_file, 'lxml')

match = soup.title

print(match)


---------------------------------




==========================================

from bs4 import BeautifulSoup

import requests

with open('simple.html') as html_file:
soup = BeautifulSoup(html_file, 'lxml')

match = soup.title.text

print(match)

---------------------------------

Test - A Sample Website

---------------------------------

==========================================

from bs4 import BeautifulSoup

import requests

with open('simple.html') as html_file:
soup = BeautifulSoup(html_file, 'lxml')

match = soup.div

print(match)


---------------------------------




---------------------------------


==========================================

from bs4 import BeautifulSoup

import requests

with open('simple.html') as html_file:
soup = BeautifulSoup(html_file, 'lxml')

match = soup.find('div')

print(match)


---------------------------------




---------------------------------

==========================================

from bs4 import BeautifulSoup

import requests

with open('simple.html') as html_file:
soup = BeautifulSoup(html_file, 'lxml')

match = soup.find('div', class_ ='footer')

print(match)


---------------------------------




---------------------------------

==========================================

from bs4 import BeautifulSoup

import requests

with open('simple.html') as html_file:
soup = BeautifulSoup(html_file, 'lxml')

article = soup.find('div', class_ ='article')

print(article)

---------------------------------




---------------------------------

==========================================

from bs4 import BeautifulSoup

import requests

with open('simple.html') as html_file:
soup = BeautifulSoup(html_file, 'lxml')

article = soup.find('div', class_ ='article')

headline = article.h2.a.text

print(headline)

---------------------------------

Article 1 Headline

---------------------------------

==========================================

from bs4 import BeautifulSoup

import requests

with open('simple.html') as html_file:
soup = BeautifulSoup(html_file, 'lxml')

article = soup.find('div', class_ ='article')

headline = article.h2.a.text
print(headline)

summary = article.p.text
print(summary)

---------------------------------

Article 1 Headline
This is a summary of article 1

---------------------------------

==========================================

from bs4 import BeautifulSoup

import requests

with open('simple.html') as html_file:
soup = BeautifulSoup(html_file, 'lxml')

for article in soup.find_all('div', class_ ='article'):
headline = article.h2.a.text
print(headline)

summary = article.p.text
print(summary)

print()

---------------------------------

Article 1 Headline
This is a summary of article 1

Article 2 Headline
This is a summary of article 2


---------------------------------

==========================================

from bs4 import BeautifulSoup
import requests

source = requests.get('http://linuxerhan.blogspot.com').text
soup = BeautifulSoup(source, 'lxml')

print(soup.prettify())

---------------------------------




---------------------------------

==========================================

from bs4 import BeautifulSoup
import requests

source = requests.get('http://linuxerhan.blogspot.com').text
soup = BeautifulSoup(source, 'lxml')

span = soup.find('span')

print(span)
print('-'*80)
print(span.prettify())

---------------------------------




---------------------------------

==========================================

from bs4 import BeautifulSoup
import requests

source = requests.get('http://linuxerhan.blogspot.com').text
soup = BeautifulSoup(source, 'lxml')

span = soup.find('span')

headline = span.a.text
print(headline)

---------------------------------

skip to main

---------------------------------

==========================================

from bs4 import BeautifulSoup
import requests

source = requests.get('http://coreyms.com').text
soup = BeautifulSoup(source, 'lxml')


article = soup.find('article')

headline = article.h2.a.text

print(headline

---------------------------------

Python Tutorial: Zip Files – Creating and Extracting Zip Archives

---------------------------------

==========================================

from bs4 import BeautifulSoup
import requests

source = requests.get('http://coreyms.com').text
soup = BeautifulSoup(source, 'lxml')


article = soup.find('article')

print(article.prettify())

---------------------------------




---------------------------------

==========================================

from bs4 import BeautifulSoup
import requests

source = requests.get('http://coreyms.com').text
soup = BeautifulSoup(source, 'lxml')


article = soup.find('article')

summary = article.find('div', class_='entry-content').p.text

print(summary)

---------------------------------

In this video, we will be learning how to create and extract zip archives. We will start by using the zipfile module, and then we will see how to do this using the shutil module. We will learn how to do this with single files and directories, as well as learning how to use gzip as well. Let’s get started…

---------------------------------

==========================================

from bs4 import BeautifulSoup
import requests

source = requests.get('http://coreyms.com').text
soup = BeautifulSoup(source, 'lxml')


article = soup.find('article')


vid_src = article.find('iframe', class_ = 'youtube-player')
print(vid_src)

---------------------------------




---------------------------------

==========================================

from bs4 import BeautifulSoup
import requests

source = requests.get('http://coreyms.com').text
soup = BeautifulSoup(source, 'lxml')


article = soup.find('article')


vid_src = article.find('iframe', class_ = 'youtube-player')['src']
print(vid_src)


---------------------------------

https://www.youtube.com/embed/z0gguhEmWiY?version=3&rel=1&fs=1&autohide=2&showsearch=0&showinfo=1&iv_load_policy=1&wmode=transparent


---------------------------------

==========================================

from bs4 import BeautifulSoup
import requests

source = requests.get('http://coreyms.com').text
soup = BeautifulSoup(source, 'lxml')


article = soup.find('article')


vid_src = article.find('iframe', class_ = 'youtube-player')['src']

vid_id = vid_src.split('/')
print(vid_id)

---------------------------------

['https:', '', 'www.youtube.com', 'embed', 'z0gguhEmWiY?version=3&rel=1&fs=1&autohide=2&showsearch=0&showinfo=1&iv_load_policy=1&wmode=transparent']

---------------------------------

==========================================

from bs4 import BeautifulSoup
import requests

source = requests.get('http://coreyms.com').text
soup = BeautifulSoup(source, 'lxml')


article = soup.find('article')


vid_src = article.find('iframe', class_ = 'youtube-player')['src']

vid_id = vid_src.split('/')[4]
print(vid_id)

---------------------------------

z0gguhEmWiY?version=3&rel=1&fs=1&autohide=2&showsearch=0&showinfo=1&iv_load_policy=1&wmode=transparent

---------------------------------

==========================================

from bs4 import BeautifulSoup
import requests

source = requests.get('http://coreyms.com').text
soup = BeautifulSoup(source, 'lxml')


article = soup.find('article')


vid_src = article.find('iframe', class_ = 'youtube-player')['src']

vid_id = vid_src.split('/')[4]

vid_id = vid_id.split('?')[0]

print(vid_id)


---------------------------------

z0gguhEmWiY

---------------------------------

==========================================

from bs4 import BeautifulSoup
import requests

source = requests.get('http://coreyms.com').text
soup = BeautifulSoup(source, 'lxml')


article = soup.find('article')


vid_src = article.find('iframe', class_ = 'youtube-player')['src']

vid_id = vid_src.split('/')[4]

vid_id = vid_id.split('?')[0]


yt_link = f'https://youtube.com/watch?v={vid_id}'
print(yt_link)

---------------------------------

https://youtube.com/watch?v=z0gguhEmWiY

---------------------------------

==========================================

from bs4 import BeautifulSoup
import requests

source = requests.get('http://coreyms.com').text
soup = BeautifulSoup(source, 'lxml')

for article in soup.find_all('article'):
headline = article.h2.a.text
print(headline)

summary = article.find('div', class_='entry-content').p.text
print(summary)

try:

vid_src = article.find('iframe', class_='youtube-player')['src']
vid_id = vid_src.split('/')[4]
vid_id = vid_id.split('?')[0]

yt_link = f'https://youtube.com/watch?v={vid_id}'

except Exception as e:
yt_link = None

print(yt_link)

print()

---------------------------------

Python Tutorial: Zip Files – Creating and Extracting Zip Archives
In this video, we will be learning how to create and extract zip archives. We will start by using the zipfile module, and then we will see how to do this using the shutil module. We will learn how to do this with single files and directories, as well as learning how to use gzip as well. Let’s get started…
https://youtube.com/watch?v=z0gguhEmWiY

Python Data Science Tutorial: Analyzing the 2019 Stack Overflow Developer Survey
In this Python Programming video, we will be learning how to download and analyze real-world data from the 2019 Stack Overflow Developer Survey. This is terrific practice for anyone getting into the data science field. We will learn different ways to analyze this data and also some best practices. Let’s get started…
https://youtube.com/watch?v=_P7X8tMplsw

Python Multiprocessing Tutorial: Run Code in Parallel Using the Multiprocessing Module
In this Python Programming video, we will be learning how to run code in parallel using the multiprocessing module. We will also look at how to process multiple high-resolution images at the same time using a ProcessPoolExecutor from the concurrent.futures module. Let’s get started…
https://youtube.com/watch?v=fKl2JW_qrso

Python Threading Tutorial: Run Code Concurrently Using the Threading Module
In this Python Programming video, we will be learning how to run threads concurrently using the threading module. We will also look at how to download multiple high-resolution images online using a ThreadPoolExecutor from the concurrent.futures module. Let’s get started…
https://youtube.com/watch?v=IEEhzQoKtQU

Update (2019-09-03)
Hey everyone. I wanted to give you an update on my videos. I will be releasing videos on threading and multiprocessing within the next week. Thanks so much for your patience. I currently have a temporary recording studio setup at my Airbnb that will allow me to record and edit the threading/multiprocessing videos. I am going to be moving into my new house in 10 days and once I have my recording studio setup then you can expect much faster video releases. I really appreciate how patient everyone has been while I go through this move, especially those of you who are contributing monthly through YouTube
None

Python Quick Tip: The Difference Between “==” and “is” (Equality vs Identity)
In this Python Programming Tutorial, we will be learning the difference between using “==” and the “is” keyword when doing comparisons. The difference between these is that “==” checks to see if values are equal, and the “is” keyword checks their identity, which means it’s going to check if the values are identical in terms of being the same object in memory. We’ll learn more in the video. Let’s get started…
https://youtube.com/watch?v=mO_dS3rXDIs

Python Tutorial: Calling External Commands Using the Subprocess Module
In this Python Programming Tutorial, we will be learning how to run external commands using the subprocess module from the standard library. We will learn how to run commands, capture the output, handle errors, and also how to pipe output into other commands. Let’s get started…
https://youtube.com/watch?v=2Fp1N6dof0Y

Visual Studio Code (Windows) – Setting up a Python Development Environment and Complete Overview
In this Python Programming Tutorial, we will be learning how to set up a Python development environment in VSCode on Windows. VSCode is a very nice free editor for writing Python applications and many developers are now switching over to this editor. In this video, we will learn how to install VSCode, get the Python extension installed, how to change Python interpreters, create virtual environments, format/lint our code, how to use Git within VSCode, how to debug our programs, how unit testing works, and more. We have a lot to cover, so let’s go ahead and get started…
https://youtube.com/watch?v=-nh9rCzPJ20

Visual Studio Code (Mac) – Setting up a Python Development Environment and Complete Overview
In this Python Programming Tutorial, we will be learning how to set up a Python development environment in VSCode on MacOS. VSCode is a very nice free editor for writing Python applications and many developers are now switching over to this editor. In this video, we will learn how to install VSCode, get the Python extension installed, how to change Python interpreters, create virtual environments, format/lint our code, how to use Git within VSCode, how to debug our programs, how unit testing works, and more. We have a lot to cover, so let’s go ahead and get started…
https://youtube.com/watch?v=06I63_p-2A4

Clarifying the Issues with Mutable Default Arguments
In this Python Programming Tutorial, we will be clarifying the issues with mutable default arguments. We discussed this in my last video titled “5 Common Python Mistakes and How to Fix Them”, but I received many comments from people who were still confused. So we will be doing a deeper dive to explain exactly what is going on here. Let’s get started…
https://youtube.com/watch?v=_JGmemuINww

---------------------------------

==========================================

from bs4 import BeautifulSoup
import requests
import csv


source = requests.get('http://coreyms.com').text

soup = BeautifulSoup(source, 'lxml')

csv_file = open('cms_scrape.csv', 'w', encoding='UTF-8')

csv_writer = csv.writer(csv_file)
csv_writer.writerow(['headline', 'summary', 'video_link'])


for article in soup.find_all('article'):
headline = article.h2.a.text
print(headline)

summary = article.find('div', class_='entry-content').p.text
print(summary)

try:
vid_src = article.find('iframe', class_='youtube-player')['src']

vid_id = vid_src.split('/')[4]
vid_id = vid_id.split('?')[0]

yt_link = f'https://youtube.com/watch?v={vid_id}'

except Exception as e:
yt_link = None

print(yt_link)

print()

csv_writer.writerow([headline, summary, yt_link])

csv_file.close()

---------------------------------

Python Tutorial: Zip Files – Creating and Extracting Zip Archives
In this video, we will be learning how to create and extract zip archives. We will start by using the zipfile module, and then we will see how to do this using the shutil module. We will learn how to do this with single files and directories, as well as learning how to use gzip as well. Let’s get started…
https://youtube.com/watch?v=z0gguhEmWiY

Python Data Science Tutorial: Analyzing the 2019 Stack Overflow Developer Survey
In this Python Programming video, we will be learning how to download and analyze real-world data from the 2019 Stack Overflow Developer Survey. This is terrific practice for anyone getting into the data science field. We will learn different ways to analyze this data and also some best practices. Let’s get started…
https://youtube.com/watch?v=_P7X8tMplsw

Python Multiprocessing Tutorial: Run Code in Parallel Using the Multiprocessing Module
In this Python Programming video, we will be learning how to run code in parallel using the multiprocessing module. We will also look at how to process multiple high-resolution images at the same time using a ProcessPoolExecutor from the concurrent.futures module. Let’s get started…
https://youtube.com/watch?v=fKl2JW_qrso

Python Threading Tutorial: Run Code Concurrently Using the Threading Module
In this Python Programming video, we will be learning how to run threads concurrently using the threading module. We will also look at how to download multiple high-resolution images online using a ThreadPoolExecutor from the concurrent.futures module. Let’s get started…
https://youtube.com/watch?v=IEEhzQoKtQU

Update (2019-09-03)
Hey everyone. I wanted to give you an update on my videos. I will be releasing videos on threading and multiprocessing within the next week. Thanks so much for your patience. I currently have a temporary recording studio setup at my Airbnb that will allow me to record and edit the threading/multiprocessing videos. I am going to be moving into my new house in 10 days and once I have my recording studio setup then you can expect much faster video releases. I really appreciate how patient everyone has been while I go through this move, especially those of you who are contributing monthly through YouTube
None

Python Quick Tip: The Difference Between “==” and “is” (Equality vs Identity)
In this Python Programming Tutorial, we will be learning the difference between using “==” and the “is” keyword when doing comparisons. The difference between these is that “==” checks to see if values are equal, and the “is” keyword checks their identity, which means it’s going to check if the values are identical in terms of being the same object in memory. We’ll learn more in the video. Let’s get started…
https://youtube.com/watch?v=mO_dS3rXDIs

Python Tutorial: Calling External Commands Using the Subprocess Module
In this Python Programming Tutorial, we will be learning how to run external commands using the subprocess module from the standard library. We will learn how to run commands, capture the output, handle errors, and also how to pipe output into other commands. Let’s get started…
https://youtube.com/watch?v=2Fp1N6dof0Y

Visual Studio Code (Windows) – Setting up a Python Development Environment and Complete Overview
In this Python Programming Tutorial, we will be learning how to set up a Python development environment in VSCode on Windows. VSCode is a very nice free editor for writing Python applications and many developers are now switching over to this editor. In this video, we will learn how to install VSCode, get the Python extension installed, how to change Python interpreters, create virtual environments, format/lint our code, how to use Git within VSCode, how to debug our programs, how unit testing works, and more. We have a lot to cover, so let’s go ahead and get started…
https://youtube.com/watch?v=-nh9rCzPJ20

Visual Studio Code (Mac) – Setting up a Python Development Environment and Complete Overview
In this Python Programming Tutorial, we will be learning how to set up a Python development environment in VSCode on MacOS. VSCode is a very nice free editor for writing Python applications and many developers are now switching over to this editor. In this video, we will learn how to install VSCode, get the Python extension installed, how to change Python interpreters, create virtual environments, format/lint our code, how to use Git within VSCode, how to debug our programs, how unit testing works, and more. We have a lot to cover, so let’s go ahead and get started…
https://youtube.com/watch?v=06I63_p-2A4

Clarifying the Issues with Mutable Default Arguments
In this Python Programming Tutorial, we will be clarifying the issues with mutable default arguments. We discussed this in my last video titled “5 Common Python Mistakes and How to Fix Them”, but I received many comments from people who were still confused. So we will be doing a deeper dive to explain exactly what is going on here. Let’s get started…
https://youtube.com/watch?v=_JGmemuINww

---------------------------------



5/14/2020

Python - OOP(Object-Oriented Programming) Property Decorators - Getters, Setters, and Deleters

** OOP(Object-Oriented Programming) Property Decorators - Getters, Setters, and Deleters

==========================================

class Employee:

def __init__(self, first, last):
self.first = first
self.last = last
self.email = first + '.' + last + '@company.com'

def fullname(self):
return '{} {}'.format(self.first, self.last)


emp_1 = Employee('HAN', 'SeokDu')

print(emp_1.first)
print(emp_1.email)
print(emp_1.fullname())

---------------------------------

HAN
HAN.SeokDu@company.com
HAN SeokDu

---------------------------------

==========================================

class Employee:

def __init__(self, first, last):
self.first = first
self.last = last
self.email = first + '.' + last + '@company.com'

def fullname(self):
return '{} {}'.format(self.first, self.last)


emp_1 = Employee('HAN', 'SeokDu')

emp_1.first = 'KIM'

print(emp_1.first)
print(emp_1.email)
print(emp_1.fullname())

---------------------------------

KIM
HAN.SeokDu@company.com
KIM SeokDu

---------------------------------

==========================================

class Employee:

def __init__(self, first, last):
self.first = first
self.last = last

def email(self):
return '{} {}@company.com'.format(self.first, self.last)

def fullname(self):
return '{} {}'.format(self.first, self.last)


emp_1 = Employee('HAN', 'SeokDu')

emp_1.first = 'KIM'

print(emp_1.first)
print(emp_1.email())
print(emp_1.fullname())

---------------------------------

KIM
KIM SeokDu@company.com
KIM SeokDu

---------------------------------

==========================================

class Employee:

def __init__(self, first, last):
self.first = first
self.last = last

@property
def email(self):
return '{} {}@company.com'.format(self.first, self.last)

@property
def fullname(self):
return '{} {}'.format(self.first, self.last)

@fullname.setter
def fullname(self, name):
first, last = name.split(' ')
self.first = first
self.last = last


emp_1 = Employee('HAN', 'SeokDu')

emp_1.fullname = 'KIM Young'

print(emp_1.first)
print(emp_1.email)
print(emp_1.fullname)

---------------------------------

KIM
KIM Young@company.com
KIM Young

---------------------------------

==========================================

# Python Object-Oriented Programming

class Employee:

def __init__(self, first, last):
self.first = first
self.last = last

@property
def email(self):
return '{} {}@company.com'.format(self.first, self.last)

@property
def fullname(self):
return '{} {}'.format(self.first, self.last)

@fullname.setter
def fullname(self, name):
first, last = name.split(' ')
self.first = first
self.last = last

@fullname.deleter
def fullname(self):
print('Delete Name!')
self.first = None
self.last = None


emp_1 = Employee('HAN', 'SeokDu')

emp_1.fullname = 'KIM Young'

print(emp_1.first)
print(emp_1.email)
print(emp_1.fullname)

del emp_1.fullname

---------------------------------

KIM
KIM Young@company.com
KIM Young
Delete Name!

---------------------------------

Python - OOP(Object-Oriented Programming) Special (Magic/Dunder) Methods

** OOP(Object-Oriented Programming) Special (Magic/Dunder) Methods


==========================================

print(1 + 2)
print('a' + 'b')

---------------------------------

3
ab

---------------------------------

==========================================


class Employee:

raise_amt = 1.04

def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'

def fullname(self):
return '{} {}'.format(self.first, self.last)

def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)


emp_1 = Employee('HAN', 'SeokDu', 50000)
emp_2 = Employee('KIM', 'Employee', 20000)

print(emp_1)

---------------------------------

__main__.Employee object at 0x00C11D18

---------------------------------

==========================================

class Employee:

raise_amt = 1.04

def __init__(self, first, last, pay):
self.first = first
self.last = last
self.email = first + '.' + last + '@company.com'
self.pay = pay

def fullname(self):
return '{} {}'.format(self.first, self.last)

def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)

def __repr__(self):
return "Employee('{}', '{}', {})".format(self.first, self.last, self.pay)

def __str__(self):
return "{} - {}".format(self.fullname(), self.email)

emp_1 = Employee('HAN', 'SeokDu', 50000)
emp_2 = Employee('KIM', 'Employee', 20000)

print(repr(emp_1))
print(str(emp_1))

---------------------------------

Employee('HAN', 'SeokDu', 50000)
HAN SeokDu - HAN.SeokDu@company.com

---------------------------------

==========================================

print(1 + 2)

print(int.__add__(1,2))

print(str.__add__('a', 'b'))

print(len('test'))

print('test'.__len__())

---------------------------------

3
3
ab
4
4

---------------------------------

==========================================

class Employee:

raise_amt = 1.04

def __init__(self, first, last, pay):
self.first = first
self.last = last
self.email = first + '.' + last + '@company.com'
self.pay = pay

def fullname(self):
return '{} {}'.format(self.first, self.last)

def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)

def __repr__(self):
return "Employee('{}', '{}', {})".format(self.first, self.last, self.pay)

def __str__(self):
return "{} - {}".format(self.fullname(), self.email)

def __add__(self, other):
return self.pay + other.pay


emp_1 = Employee('HAN', 'SeokDu', 50000)
emp_2 = Employee('KIM', 'Employee', 20000)

print(emp_1 + emp_2)

---------------------------------

70000

---------------------------------

==========================================

class Employee:

raise_amt = 1.04

def __init__(self, first, last, pay):
self.first = first
self.last = last
self.email = first + '.' + last + '@company.com'
self.pay = pay

def fullname(self):
return '{} {}'.format(self.first, self.last)

def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)

def __repr__(self):
return "Employee('{}', '{}', {})".format(self.first, self.last, self.pay)

def __str__(self):
return "{} - {}".format(self.fullname(), self.email)

# def __add__(self, other):
# return self.pay + other.pay


emp_1 = Employee('HAN', 'SeokDu', 50000)
emp_2 = Employee('KIM', 'Employee', 20000)

print(emp_1 + emp_2)

---------------------------------

    print(emp_1 + emp_2)
TypeError: unsupported operand type(s) for +: 'Employee' and 'Employee'

---------------------------------

==========================================

https://docs.python.org/3.8/reference/datamodel.html?highlight=__add__#emulating-numeric-types

==========================================

class Employee:

raise_amt = 1.04

def __init__(self, first, last, pay):
self.first = first
self.last = last
self.email = first + '.' + last + '@company.com'
self.pay = pay

def fullname(self):
return '{} {}'.format(self.first, self.last)

def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)

def __repr__(self):
return "Employee('{}', '{}', {})".format(self.first, self.last, self.pay)

def __str__(self):
return "{} - {}".format(self.fullname(), self.email)

def __add__(self, other):
return self.pay + other.pay

def __len__(self):
return len(self.fullname())

emp_1 = Employee('HAN', 'SeokDu', 50000)
emp_2 = Employee('KIM', 'Employee', 20000)

print(len(emp_1))

---------------------------------

10

---------------------------------



Python - OOP(Object-Oriented Programming) Inheritance - Creating Subclasses

** OOP(Object-Oriented Programming) Inheritance - Creating Subclasses


==========================================

# Python Object-Oriented Programming

class Employee:

num_of_emps = 0
raise_amt = 1.04

def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'

Employee.num_of_emps += 1

def fullname(self):
return '{} {}'.format(self.first, self.last)

def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)


class Developer(Employee):
pass



dev_1 = Employee('HAN', 'SeokDu', 50000)
dev_2 = Employee('KIM', 'Young', 30000)

print(dev_1.email)
print(dev_2.email)

---------------------------------

HAN.SeokDu@company.com
KIM.Young@company.com

---------------------------------

==========================================

# Python Object-Oriented Programming

class Employee:

num_of_emps = 0
raise_amt = 1.04

def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'

Employee.num_of_emps += 1

def fullname(self):
return '{} {}'.format(self.first, self.last)

def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)


class Developer(Employee):
pass


dev_1 = Developer('HAN', 'SeokDu', 50000)
dev_2 = Developer('KIM', 'Young', 30000)

print(dev_1.email)
print(dev_2.email)

---------------------------------

HAN.SeokDu@company.com
KIM.Young@company.com

---------------------------------

==========================================

class Employee:

num_of_emps = 0
raise_amt = 1.04

def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'

Employee.num_of_emps += 1

def fullname(self):
return '{} {}'.format(self.first, self.last)

def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)


class Developer(Employee):
pass


dev_1 = Developer('HAN', 'SeokDu', 50000)
dev_2 = Developer('KIM', 'Young', 30000)

print(help(Developer))

---------------------------------

Help on class Developer in module __main__:

class Developer(Employee)
 |  Developer(first, last, pay)
 | 
 |  Method resolution order:
 |      Developer
 |      Employee
 |      builtins.object
 | 
 |  Methods inherited from Employee:
 | 
 |  __init__(self, first, last, pay)
 |      Initialize self.  See help(type(self)) for accurate signature.
 | 
 |  apply_raise(self)
 | 
 |  fullname(self)
 | 
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from Employee:
 | 
 |  __dict__
 |      dictionary for instance variables (if defined)
 | 
 |  __weakref__
 |      list of weak references to the object (if defined)
 | 
 |  ----------------------------------------------------------------------
 |  Data and other attributes inherited from Employee:
 | 
 |  num_of_emps = 2
 | 
 |  raise_amt = 1.04

None

---------------------------------

==========================================

class Employee:

num_of_emps = 0
raise_amt = 1.04

def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'

Employee.num_of_emps += 1

def fullname(self):
return '{} {}'.format(self.first, self.last)

def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)


class Developer(Employee):
pass


dev_1 = Developer('HAN', 'SeokDu', 50000)
dev_2 = Developer('KIM', 'Young', 30000)

# print(dev_1.email)
# print(dev_2.email)

print(dev_1.pay)
dev_1.apply_raise()
print(dev_1.pay)

---------------------------------

50000
52000

---------------------------------

==========================================

class Employee:

num_of_emps = 0
raise_amt = 1.04

def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'

Employee.num_of_emps += 1

def fullname(self):
return '{} {}'.format(self.first, self.last)

def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)


class Developer(Employee):
raise_amt = 1.10


dev_1 = Developer('HAN', 'SeokDu', 50000)
dev_2 = Developer('KIM', 'Young', 30000)

print(dev_1.pay)
dev_1.apply_raise()
print(dev_1.pay)

---------------------------------

50000
55000

---------------------------------

==========================================

class Employee:

num_of_emps = 0
raise_amt = 1.04

def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'

Employee.num_of_emps += 1

def fullname(self):
return '{} {}'.format(self.first, self.last)

def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)


class Developer(Employee):
raise_amt = 1.10


dev_1 = Employee('HAN', 'SeokDu', 50000)
dev_2 = Developer('KIM', 'Young', 30000)

print(dev_1.pay)
dev_1.apply_raise()
print(dev_1.pay)

---------------------------------

50000
52000

---------------------------------

==========================================

class Employee:

num_of_emps = 0
raise_amt = 1.04

def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'

Employee.num_of_emps += 1

def fullname(self):
return '{} {}'.format(self.first, self.last)

def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)


class Developer(Employee):
raise_amt = 1.10

def __init__(self, first, last, pay, prog_lang):
super().__init__(first, last, pay)
self.prog_lang = prog_lang


dev_1 = Developer('HAN', 'SeokDu', 50000, 'Python')
dev_2 = Developer('KIM', 'Young', 30000, 'Java')

print(dev_1.email)
print(dev_1.prog_lang)

---------------------------------

HAN.SeokDu@company.com
Python

---------------------------------

==========================================

class Employee:

num_of_emps = 0
raise_amt = 1.04

def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'

Employee.num_of_emps += 1

def fullname(self):
return '{} {}'.format(self.first, self.last)

def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)


class Developer(Employee):
raise_amt = 1.10

def __init__(self, first, last, pay, prog_lang):
super().__init__(first, last, pay)
self.prog_lang = prog_lang

class Manager(Employee):

def __init__(self, first, last, pay, employees = None):
super().__init__(first, last, pay)
if employees is None:
self.employees = []
else:
self.employees = employees

def add_emp(self, emp):
if emp not in self.employees:
self.employees.append(emp)

def remove_emp(self, emp):
if emp in self.employees:
self.employees.remove(emp)

def print_emps(self):
for emp in self.employees:
print('-->', emp.fullname())


dev_1 = Developer('HAN', 'SeokDu', 50000, 'Python')
dev_2 = Developer('KIM', 'Young', 30000, 'Java')

mgr_1 = Manager('Sue', 'Smith', 90000, [dev_1])

print(mgr_1.email)

mgr_1.print_emps()


---------------------------------

Sue.Smith@company.com
--> HAN SeokDu

---------------------------------

==========================================

class Employee:

num_of_emps = 0
raise_amt = 1.04

def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'

Employee.num_of_emps += 1

def fullname(self):
return '{} {}'.format(self.first, self.last)

def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)


class Developer(Employee):
raise_amt = 1.10

def __init__(self, first, last, pay, prog_lang):
super().__init__(first, last, pay)
self.prog_lang = prog_lang

class Manager(Employee):

def __init__(self, first, last, pay, employees = None):
super().__init__(first, last, pay)
if employees is None:
self.employees = []
else:
self.employees = employees

def add_emp(self, emp):
if emp not in self.employees:
self.employees.append(emp)

def remove_emp(self, emp):
if emp in self.employees:
self.employees.remove(emp)

def print_emps(self):
for emp in self.employees:
print('-->', emp.fullname())


dev_1 = Developer('HAN', 'SeokDu', 50000, 'Python')
dev_2 = Developer('KIM', 'Young', 30000, 'Java')

mgr_1 = Manager('Sue', 'Smith', 90000, [dev_1])

print(mgr_1.email)

mgr_1.add_emp(dev_2)

mgr_1.print_emps()

---------------------------------

Sue.Smith@company.com
--> HAN SeokDu
--> KIM Young

---------------------------------

==========================================

class Employee:

num_of_emps = 0
raise_amt = 1.04

def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'

Employee.num_of_emps += 1

def fullname(self):
return '{} {}'.format(self.first, self.last)

def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)


class Developer(Employee):
raise_amt = 1.10

def __init__(self, first, last, pay, prog_lang):
super().__init__(first, last, pay)
self.prog_lang = prog_lang

class Manager(Employee):

def __init__(self, first, last, pay, employees = None):
super().__init__(first, last, pay)
if employees is None:
self.employees = []
else:
self.employees = employees

def add_emp(self, emp):
if emp not in self.employees:
self.employees.append(emp)

def remove_emp(self, emp):
if emp in self.employees:
self.employees.remove(emp)

def print_emps(self):
for emp in self.employees:
print('-->', emp.fullname())


dev_1 = Developer('HAN', 'SeokDu', 50000, 'Python')
dev_2 = Developer('KIM', 'Young', 30000, 'Java')

mgr_1 = Manager('Sue', 'Smith', 90000, [dev_1])

print(mgr_1.email)

mgr_1.add_emp(dev_2)
mgr_1.remove_emp(dev_1)

mgr_1.print_emps()

---------------------------------

Sue.Smith@company.com
--> KIM Young

---------------------------------

==========================================

class Employee:

num_of_emps = 0
raise_amt = 1.04

def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'

Employee.num_of_emps += 1

def fullname(self):
return '{} {}'.format(self.first, self.last)

def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)


class Developer(Employee):
raise_amt = 1.10

def __init__(self, first, last, pay, prog_lang):
super().__init__(first, last, pay)
self.prog_lang = prog_lang

class Manager(Employee):

def __init__(self, first, last, pay, employees = None):
super().__init__(first, last, pay)
if employees is None:
self.employees = []
else:
self.employees = employees

def add_emp(self, emp):
if emp not in self.employees:
self.employees.append(emp)

def remove_emp(self, emp):
if emp in self.employees:
self.employees.remove(emp)

def print_emps(self):
for emp in self.employees:
print('-->', emp.fullname())


dev_1 = Developer('HAN', 'SeokDu', 50000, 'Python')
dev_2 = Developer('KIM', 'Young', 30000, 'Java')

mgr_1 = Manager('Sue', 'Smith', 90000, [dev_1])


print(isinstance(mgr_1, Manager))
print(isinstance(mgr_1, Employee))
print(isinstance(mgr_1, Developer))

print("-"*80)

print(issubclass(Developer, Employee))
print(issubclass(Manager, Employee))
print(issubclass(Manager, Developer))

---------------------------------

True
True
False
--------------------------------------------------------------------------------
True
True
False

---------------------------------