\documentclass[10pt,a4paper]{article} % Packages \usepackage{fancyhdr} % For header and footer \usepackage{multicol} % Allows multicols in tables \usepackage{tabularx} % Intelligent column widths \usepackage{tabulary} % Used in header and footer \usepackage{hhline} % Border under tables \usepackage{graphicx} % For images \usepackage{xcolor} % For hex colours %\usepackage[utf8x]{inputenc} % For unicode character support \usepackage[T1]{fontenc} % Without this we get weird character replacements \usepackage{colortbl} % For coloured tables \usepackage{setspace} % For line height \usepackage{lastpage} % Needed for total page number \usepackage{seqsplit} % Splits long words. %\usepackage{opensans} % Can't make this work so far. Shame. Would be lovely. \usepackage[normalem]{ulem} % For underlining links % Most of the following are not required for the majority % of cheat sheets but are needed for some symbol support. \usepackage{amsmath} % Symbols \usepackage{MnSymbol} % Symbols \usepackage{wasysym} % Symbols %\usepackage[english,german,french,spanish,italian]{babel} % Languages % Document Info \author{cgeeeeh} \pdfinfo{ /Title (oop.pdf) /Creator (Cheatography) /Author (cgeeeeh) /Subject (OOP Cheat Sheet) } % Lengths and widths \addtolength{\textwidth}{6cm} \addtolength{\textheight}{-1cm} \addtolength{\hoffset}{-3cm} \addtolength{\voffset}{-2cm} \setlength{\tabcolsep}{0.2cm} % Space between columns \setlength{\headsep}{-12pt} % Reduce space between header and content \setlength{\headheight}{85pt} % If less, LaTeX automatically increases it \renewcommand{\footrulewidth}{0pt} % Remove footer line \renewcommand{\headrulewidth}{0pt} % Remove header line \renewcommand{\seqinsert}{\ifmmode\allowbreak\else\-\fi} % Hyphens in seqsplit % This two commands together give roughly % the right line height in the tables \renewcommand{\arraystretch}{1.3} \onehalfspacing % Commands \newcommand{\SetRowColor}[1]{\noalign{\gdef\RowColorName{#1}}\rowcolor{\RowColorName}} % Shortcut for row colour \newcommand{\mymulticolumn}[3]{\multicolumn{#1}{>{\columncolor{\RowColorName}}#2}{#3}} % For coloured multi-cols \newcolumntype{x}[1]{>{\raggedright}p{#1}} % New column types for ragged-right paragraph columns \newcommand{\tn}{\tabularnewline} % Required as custom column type in use % Font and Colours \definecolor{HeadBackground}{HTML}{333333} \definecolor{FootBackground}{HTML}{666666} \definecolor{TextColor}{HTML}{333333} \definecolor{DarkBackground}{HTML}{FFBB98} \definecolor{LightBackground}{HTML}{FFF6F2} \renewcommand{\familydefault}{\sfdefault} \color{TextColor} % Header and Footer \pagestyle{fancy} \fancyhead{} % Set header to blank \fancyfoot{} % Set footer to blank \fancyhead[L]{ \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{C} \SetRowColor{DarkBackground} \vspace{-7pt} {\parbox{\dimexpr\textwidth-2\fboxsep\relax}{\noindent \hspace*{-6pt}\includegraphics[width=5.8cm]{/web/www.cheatography.com/public/images/cheatography_logo.pdf}} } \end{tabulary} \columnbreak \begin{tabulary}{11cm}{L} \vspace{-2pt}\large{\bf{\textcolor{DarkBackground}{\textrm{OOP Cheat Sheet}}}} \\ \normalsize{by \textcolor{DarkBackground}{cgeeeeh} via \textcolor{DarkBackground}{\uline{cheatography.com/191000/cs/39808/}}} \end{tabulary} \end{multicols}} \fancyfoot[L]{ \footnotesize \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{LL} \SetRowColor{FootBackground} \mymulticolumn{2}{p{5.377cm}}{\bf\textcolor{white}{Cheatographer}} \\ \vspace{-2pt}cgeeeeh \\ \uline{cheatography.com/cgeeeeh} \\ \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Cheat Sheet}} \\ \vspace{-2pt}Not Yet Published.\\ Updated 7th August, 2023.\\ Page {\thepage} of \pageref{LastPage}. \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Sponsor}} \\ \SetRowColor{white} \vspace{-5pt} %\includegraphics[width=48px,height=48px]{dave.jpeg} Measure your website readability!\\ www.readability-score.com \end{tabulary} \end{multicols}} \begin{document} \raggedright \raggedcolumns % Set font size to small. Switch to any value % from this page to resize cheat sheet text: % www.emerson.emory.edu/services/latex/latex_169.html \footnotesize % Small font. \begin{multicols*}{2} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{class}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{\seqsplit{\#类的名字应该用大写字母} \newline class Employee: \newline \#给一些定义 \newline """ define a class for all employee \newline instances in a company """ \newline \#没啥内容就写pass \newline pass \newline \newline \#创建一个实体 \newline variable\_name = Employee()} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Attributes}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{instance attributes \seqsplit{是每个实体都有自己的} \newline \# Provide attributes and assign values to the instances \newline emp1.firstName = "Maria" \newline emp1.lastName = "Rena" \newline emp1.basicSalary = 12000 \newline emp1.allowance = 5000 \newline \newline class attributes belong to the class itself, and are thus shared among all instances of the class \newline 如果先声明instant \seqsplit{attribute,再声明class} \seqsplit{attribute。那不会覆盖原来的instant} attribute。 \newline 但如果原来在类里声明了一个类attribute,在后面再修改,那原来的值确实会被覆盖 \newline \newline obj.\_\_dict\_\_返回【实体】和它的所有方法 \newline class.\_\_dict\_\_返回【类】的所有方法和属性} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Methods}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{instant method是自定义的 \newline class Employee: \newline bonusPercent = 0.2 \newline \# Define an instance method that takes no arguments \newline def calculateBonus(self): \newline return self.salary * Employee.bonusPercent \newline \newline 如何更改bonusPercent的默认值?用类的调用来改 \newline Employee.bonusPercent=0.3 \newline \newline Constructor \& Destructor Method \seqsplit{是内置的建立和销毁函数} \newline \_\_init\_\_,\_\_del\_\_,\_\_str\_\_} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{\seqsplit{使用默认参数初始化实例}}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{\seqsplit{\#这段代码有条件才执行,如果不执行的话这个实例四个attribute都不会有} \newline def \_\_init\_\_ (self, first = None, last = None, salary = None, allowances = None): \newline if first!= None and last!= None and salary!= None and allowances!= None: \newline self.firstName = first \newline self.lastName = last \newline self.salary = salary \newline self.allowances = allowances \newline print("Object initialized with supplied values")} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{写入和加载obj}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{import \_pickle as cpickle \newline class stock: \newline def \_\_init\_\_(self, name, lots): \newline self.name = name \newline self.lots = lots \newline def \_\_str\_\_(self): \newline return f'\{self.name\}=\textgreater{}\{self.lots\}' \newline \newline \#写入 \newline s1 = stock("Apple",1500) \newline s2 = stock("Google",2000) \newline with open("s1.obj", "wb") as f: \newline cpickle.dump(s1/{[}s1,s2{]}, f) \newline \newline \#加载 \newline with open("s1.obj", "rb") as f: \newline s1 = cpickle.load(f) \newline print(s1) \newline with open("ss.obj", "rb") as f: \newline data = cpickle.load(f) \newline for each in data: \newline print(each)} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{\seqsplit{self.variable和class.variable的区别}}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{class employee: \newline count=5 \newline def \_\_init\_\_(self,x): \newline self.x=x \newline self.count=self.count+1 \newline print ("this method is executed") \newline print (self.count) \newline print (employee.count) \newline \newline emp1=employee("John") \newline emp1.count+=1 \newline print(emp1.count) \newline print(employee.count) \newline \newline 结果是6,5,7,5。self.variable显示的是这个obj自己当前的值,class.variable显示的是他们共用的初始值} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{JSON \seqsplit{data(json,dict和obj可以互相转化)}}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{\seqsplit{\#把obj放进json再取出来} \newline import json \newline from json import JSONEncoder \newline \newline class stock(object): \newline def \_\_init\_\_(self, name, lots): \newline self.name = name \newline self.lots = lots \newline def \_\_str\_\_(self): \newline return f'\{self.name\}=\textgreater{}\{self.lots\}' \newline \newline class \seqsplit{StockEncoder(JSONEncoder):} \newline def default(self, o): \newline return o.\_\_dict\_\_ \newline \newline s1 = stock("Apple",1500) \newline \newline \# encode Object it \newline s1Json = json.dumps(s1, cls=StockEncoder, indent=4) \newline ''' \newline json.loads() method can be used to parse a valid JSON string and convert it into a Python Dictionary. \newline ''' \newline resultDict = json.loads(s1Json) \newline s1Obj = stock({\bf{resultDict) \newline \newline \#json data写入/存储 \newline with \seqsplit{open("stockPrettyPrint.json"}, "w") as write\_file: \newline json.dump(s1, write\_file,cls=StockEncoder, indent=4) \newline with \seqsplit{open("stockPrettyPrint.json"}, "r") as read\_file: \newline s = json.load(read\_file) \newline PrettyJson = json.dumps(s, indent=4, separators=(',', ': '), sort\_keys=True) \newline \newline \#Json, Dictionary, object \newline import json \newline from json import JSONEncoder \newline \newline class stock(object): \newline def \_\_init\_\_(self, name, lots): \newline self.name = name \newline self.lots = lots \newline def \_\_str\_\_(self): \newline return f'\{self.name\}=\textgreater{}\{self.lots\}' \newline \newline class \seqsplit{StockEncoder(JSONEncoder):} \newline def default(self, o): \newline return o.\_\_dict\_\_ \newline def StockDecoder(obj): \newline if '\_\_type\_\_' in obj and obj{[}'\_\_type\_\_'{]} =='stock': \newline return stock(obj{[}'name'{]}, obj{[}'lots'{]}) \newline return obj \newline \newline s2Obj = json.loads('\{"\_\_type\_\_": "stock", "lots":2000, "name": "Google"\}', \seqsplit{object\_hook=StockDecoder)} \newline \newline with \seqsplit{open("stockPrettyPrint.json"}, "w") as write\_file: \newline json.dump({[}s2Obj{]}, write\_file,cls=StockEncoder, indent=4)) \newline with \seqsplit{open("stockPrettyPrint.json"}, "r") as read\_file: \newline print("Read JSON file") \newline s = json.load(read\_file) \newline for each in s: \newline each = stock(}}each) \newline print(each)} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{JSON \seqsplit{data(json,dict和obj是可以互转)}}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{\seqsplit{\#把obj放进json再取出来} \newline import json \newline from json import JSONEncoder \newline \newline class stock(object): \newline def \_\_init\_\_(self, name, lots): \newline self.name = name \newline self.lots = lots \newline def \_\_str\_\_(self): \newline return f'\{self.name\}=\textgreater{}\{self.lots\}' \newline \newline class \seqsplit{StockEncoder(JSONEncoder):} \newline def default(self, o): \newline return o.\_\_dict\_\_ \newline \newline s1 = stock("Apple",1500) \newline \newline \# encode Object it \newline s1Json = json.dumps(s1, cls=StockEncoder, indent=4) \newline ''' \newline json.loads() method can be used to parse a valid JSON string and convert it into a Python Dictionary. \newline ''' \newline resultDict = json.loads(s1Json) \newline s1Obj = stock({\bf{resultDict) \newline \newline \#json data写入/存储 \newline with \seqsplit{open("stockPrettyPrint.json"}, "w") as write\_file: \newline json.dump(s1, write\_file,cls=StockEncoder, indent=4) \newline with \seqsplit{open("stockPrettyPrint.json"}, "r") as read\_file: \newline s = json.load(read\_file) \newline PrettyJson = json.dumps(s, indent=4, separators=(',', ': '), sort\_keys=True) \newline \newline \#Json, Dictionary, object \newline import json \newline from json import JSONEncoder \newline \newline class stock(object): \newline def \_\_init\_\_(self, name, lots): \newline self.name = name \newline self.lots = lots \newline def \_\_str\_\_(self): \newline return f'\{self.name\}=\textgreater{}\{self.lots\}' \newline \newline class \seqsplit{StockEncoder(JSONEncoder):} \newline def default(self, o): \newline return o.\_\_dict\_\_ \newline def StockDecoder(obj): \newline if '\_\_type\_\_' in obj and obj{[}'\_\_type\_\_'{]} =='stock': \newline return stock(obj{[}'name'{]}, obj{[}'lots'{]}) \newline return obj \newline \newline s2Obj = json.loads('\{"\_\_type\_\_": "stock", "lots":2000, "name": "Google"\}', \seqsplit{object\_hook=StockDecoder)} \newline \newline with \seqsplit{open("stockPrettyPrint.json"}, "w") as write\_file: \newline json.dump({[}s2Obj{]}, write\_file,cls=StockEncoder, indent=4)) \newline with \seqsplit{open("stockPrettyPrint.json"}, "r") as read\_file: \newline print("Read JSON file") \newline s = json.load(read\_file) \newline for each in s: \newline each = stock(}}each) \newline print(each)} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} % That's all folks \end{multicols*} \end{document}