CCChapter 8 and maybe more Flashcards
Use a dataclass to automatically create your __init__ and your instance variables
Give one default argument
from dataclasses import dataclass
@dataclass
class Customer:
name: str
city: str
age: int = 33
What are things like @dataclass and @property called?
decorators
Add all arguments to the dataclass decorator and describe their functionality
@dataclass(init=True, repr=True, eq=True, order=False, frozen=False)
init - defaults to true and auto creates __init__ method
repr - defaults to True and allows class to represent itself as a string, used to compare object usually. repr() will call this method on the class to obtain the string.
eq - defaults to true and the __eq__ method will compare two object of the same class.
order - defaults to false and does comparisons like equals, except with __lt__ __le__ __gt__ __ge__
frozen - defaults to false, if true it makes everything in class immutable which would allow it to be stored in a set or dictionary
Use the repr argument
from dataclasses import dataclass
@dataclass
class Customer:
name = str
age = int
c1 = Customer(“Nathan”, 33)
print(repr(c1))
Use the eq argument
from dataclasses import dataclass
@dataclass
class Customer:
name = str
age = int
c1 = Customer(“Nathan”, 33)
c2 = Customer(“Jeremy”, 28)
print(c1 == c2)
Module
Group of code that can be classes, variables, or functions all working together, a module works in it’s own namespace separate from the Main Program (global namespace)
Namespaces and importing
Importing grabs a module and makes it accessible to you. The module exists in it’s own namespace, like the module “locale”.
If we import locale:
import locale we can’t access locale_alias because it exists in the module’s namespace. You access it like this
locale.locale_alias
Give the locale module a new name
import locale as robert
robert.locale_alias
Lets say we want to use the parser code from the email module and that’s it, how would we do that?
from email import parser
Show all variables, then show all methods, then finally show helpful info for the email module
vars(email)
dir(email)
help(email)
How would you create a module
Save a file that you have made for a class that can actually do something.
Open a new file.
import distance (name of the file minus the .py bit)
dist = distance.Distance(3)
making an object in the new file that denotes the module “distance” then adds the class, followed by the argument Distance(3)
now use it like you would from the module itself.
print(dist.miles)
FILES MUST BE IN THE SAME DIRECTORY
What is a package?
Create one. Remember, we have everything we need except one file to make it easier.
In the directory with your current project add the files you want as a part of your package into a folder called “calculations”.
Add all your python files to this.
Next, add a file called __init__.py
import everything using this file:
from .distance import *
from .area import *
from .timecalc import *
On your current project:
import calculations
object = calculations.Distance(3)
print(object.km)
Create a variable with the string “Hello, World”
Create an if statement that says if World isn’t in the equal to -1 then to do something. (Also, what number would pop up for world?)
inside the if statement replace “World” with “Reader”
create a string
a = “Hello, World”
search for world in the string
if a.find(“World”) != -1:
# Replace "World with Reader" b = a.replace("World", "Reader") # Display the results print(a) print("... was replaced with ...") print(b)
You could also just do print(a.replace(“World”, “Reader”))
Create the variable “title” with comprised of the string “Python Quick Start Guide”
Show it in all uppercase and then all lower case.
title = “Python Quick Start Guide”
print(title.upper())
print(title.lower())
create a variable and string combination:
tongue_twister = “She sells sea shells by the seashore.”
Show the count of every time an “s” was displayed.
print(tongue_twister.count(s))
Take each character from a string and put it into a list
Put it back together again
fox = quick fox
list = fox.split()
print(list)
list = ““.join(fox)
Create a string that contains the following:
123-45-6789
print this as if every “-“ is a space to add them as their own item in a list.
Use “-“ as your delimiter basically
id = “123-45-6789
id_s = id.split(“-“)
print(id_s)
you can also make a split calling multiple delimiters:
glossary = “This, and, that”
gl = glossary.split(“, “)
print(gl)
Create a variable with the below string:
“delimiter, module, package, class, object”
Put each item individually in a list
Now return them to the way they were.
glossary = “delimiter, module, package, class, object”
print (glossary)
glossary_list = glossary.split(“, “)
print(glossary_list)
glossary_list = “, “.join(glossary_list)
print(glossary_list)
Create an input variable
Have python return whether it is:
numeric
alphabetic
alphanumeric
Explain what works here
Firstly, this only works if there are no spaces.
Secondly Alphanumeric will pop up if it’s either one or the other
value = input(“Please enter a vlaue: “)
if value.isnumeric():
print(“It’s a number!”)
Check if every character is a letter”
if value.isalpha():
print(“It is filled with alphabet characters only!”)
if value.isalnum():
print(“It is alphanumeric!”)
What are regular expressions?
String of characters and special codes that are designed to match certain patterns in strings.
Import regular expressions
create a string “Hello, World!”
Search for “hello” within the string
using regular expressions, remember to add a flag in
import re
text = “Hello, World!”
if re.search(“Hello”, text, re.IGNORECASE):
print(“Hello is in the string”)
else:
print(“Hello isn’t in the string”)
You can also use re.I to do the same thing
Create the string:
“the quick gray fox jumped over the lazy dog”
Search if gray or grey is used in the sentence with regex.
print the match
print where the word is located in the sentence
import re
text = “The quick gray fox jumped over the lazy dog”
match = re.search(“(gray|grey)”, text, re.IGNORECASE)
print(match.group(0))
create a variable with “The quick gray fox jumped over the lazy dog”
Search for whether “grey” or “gray” was used.
store the position of the beginning of the word grey in the sentence into a variable
store the position of the end of the word grey in the sentence into a variable
Using the numbered positions. swap the word grey out for gray
text = “The quick gray fox jumped over the lazy dog”
match = re.search(“(gray|grey)”, text, re.IGNORECASE)
match_start = match.span()[0]
match_end = match.span()[1]
replace_text = “grey”
new_text = text[:match_start] + replace_text + text[match_end:]
print(“old text: “ + text)
print(“new text: “ + new_text)
[:this] and [this:] tell python:
[:this] < - give me everything up until before this point
[this:] give me everything after and including this point this point
Using a regex anchor print if the string starts with “h” or not
import re
text = “Hello, World”
if re.search(“^H”, text):
print(“String starts with H”)
Using a regex anchor, print if a string ends with and exclamation point
import re
text = “Hello, World!”
if re.search(“!$”, text):
print(“String ends with exclamation”)
When we use the \ this means we want to use the literal character rather than a regex symbol.
How would regex check if the first or last word in every line of a multiline string is a certain word. (This doesn’t mean they all need to start with the word, just that one of them has it.)
How would you change this slightly to make sure it would only search the beginning or the end of the string?
import re
text = “"”This is a multiline string.
It has multiple lines to it.
So, fittingly, it’s called a multiline string.
When you type a string and hit ENTER,
a special character is inserted in the string.
That special character is a backslash followed by n.”””
if re.search(“^It”, text, re.MULTILINE):
print(“yes”)
else:
print(“no”)
re.MULTILINE flag tells to check everyline for this, not just the beginning of the string.
For just beginning of the string
if re.search(“\AIt”, text, re.MULTILINE):
For just the end of the string
if re.search(“It\Z”, text, re.MULTILINE):
What’s the faster way of searching for words at the beginning of a string?
Use that and compare it to re.search doing the same thing looking for a character in the middle of a sentence
import re
test = “Hello, World!”
if re.match(“e”, test):
print(“e in it”)
if re.search(“e”, test):
print(“e in it also”)
Split an string using regex into a list, use space as a delimiter in two different ways
import re
test = “The quick brown fox is fast!”
space = re.split(“\s+”, test)
print(space)
spacer = re.split(“\W+”, test)
print(spacer)
\s <- white space
\W <- non word character
+ <- match one or more
Create a string
replace spaces with +’s
import re
test = “The quick brown fox is fast!”
plus_test = re.sub(“\s+”, “+”, test)
print(plus_test)
remember:
\s < - white space
+ < - one or more
Using string formatting, print the string:
“Hello !”
place a name variable inside that you’ve defined earlier
Next create a greeting variable that will let you add information to it via print using string formatting
name = “Frank”
print(“Hello {}!”.format(name))
greeting = “Hello, {name}! I hear you’re {age} years old”
print(greeting.format(name = “Nathan”, age = 33))
Convert a number to a float using string formatting
You can do this via two variables and then print at the end
number = 6.99
message = “Your total is {:.2f}”
print(message.format(number))
: <- This tells the format formatting code is coming
.2 <- I need two decimal places
f <- make my boy here a float
Create a multiline string
compress it
compare amount of characters in original to compressed data
Don’t forget UTF-8!
UTF-8 has a bit more in it then just english numbers and letters
import zlib
data = “"”This is a multiline string.
We are using this as a test to compare
the before and after affects of compression.
Let this serve as a warning to any woman who dares
disrespect my virginity by attempting to have sex with me.
Away, wench! I will cry ha ha! Away with thee! I must study!!”””
We have to convert from ASCII to UTF-8 in order to compress
compressed = zlib.compress(data.encode())
print(len(data))
print(len(compressed))