Skip to content
Home » University of Michigan » Python for Everybody Specialization » Using Databases with Python » Week 1: Object Oriented Python

Week 1: Object Oriented Python

Before we jump into building our own objects, let’s take a step back and explore the world of Object-Oriented (OO) Python. It might seem a little abstract at first, but understanding these key concepts will unlock the magic behind many tools you already use, like BeautifulSoup, strings, dictionaries, and even database connections. Think of it as learning the language of objects: verbs, nouns, and how they interact.

Here’s what we’ll cover:

  • Basic OO patterns: Dive into concepts like classes, objects, attributes, and methods. Learn what they are and how they work together.
  • Terminology decoded: Unravel terms like inheritance, polymorphism, and encapsulation. Don’t let these fancy words intimidate you; we’ll break them down in simple terms.
  • Familiar tools, new perspective: See how everyday tools like BeautifulSoup and dictionaries utilize OO principles. This understanding will empower you to use them more effectively.

Remember, the goal is not just to memorize terms, but to gain a fundamental understanding that will serve you well as you delve deeper into object creation and advanced programming concepts. Let’s unlock the power of OO Python together!


Welcome


Video: Welcome to Using Databases with Python

Key Points:

  • This is the 4th course in a series, assuming prior knowledge of Python.
  • Focuses on Object-Oriented Programming (OOP), Structured Query Language (SQL), and Database Design.
  • SQL is the main topic and considered more enjoyable than Python by many beginners.
  • SQL differs from Python in its “do it all in one statement” approach.
  • Learning SQL is valuable for many job roles.
  • The course will culminate in analysis, visualization, and scraping exercises, as a preview for the final capstone project.

Additional Notes:

  • The instructor encourages reviewing previous courses (1-3) if prerequisites haven’t been met.
  • The pace slows down compared to earlier courses due to increased complexity.
  • One-to-one relationships, foreign keys, joins, and CRUD operations (Select, Delete, Update) in SQL will be covered.

So, welcome to our Databases course. This is the fourth course in the class and if you have taken all three, you have learned a bunch. There’s a lot in this class. If you’re two weeks into this class and you didn’t take the prerequisite courses, and you’re like what are these people talking about? Well, that’s what those other courses are. Don’t say, “oh why didn’t you give me a basic intro to Python?” And the answer is we did that. That’s what courses One, Two And Three were. You’ll notice that in courses Three and Four, that we’re going more slowly through the book. The material’s more complex, the lectures take longer to develop. In this we’re going to learn Object Training Programming, we’re you’re going to learn Structured Query Language, and we’re going to do a little bit of Visualization. In a way, Structured Query Language is the the biggest part of this class. We’re going to learn about Database design, and this is so that ultimately, if you need these Databases as part of a Python program, you’re competent in Databases. So, this is more about Database than it is about Python. We’re going to learn about, like I said, Database design, One-to-One relationships, Foreign keys, Joins, Select, Delete, Update. I love SQL, Structured Query Language. I think you probably will too. Most beginning students prefer SQL, in a way to Python. Because SQL is a fundamentally different pattern for writing software. In Python you have learned that you got to be very explicit. Like do this, then do that and keep track of this other thing and then check back in that other thing, and add a thing to this other thing, and then print these stuff out and sort them. You’re like, do it and there’s a bunch of really simple kind of things that you construct. Orders and patterns and loops, and that’s what you’re good at by now. In SQL you do it all in one one statement. You’re like, do this where that happens, pull this other stuff and blah blah, blah, blah, blah, and then magically you get exactly what you want. You write single statement programs that are themselves internally interesting and complex. Like regular expressions. Regular expressions are not essential but SQL in lots of job situations is essential. So I think that you should look forward to learning SQL. It’s a fun language. It’s different, so get ready for that. Then what we do at the very end is, we do a little bit- bring it all together and do some analysis and visualization and scraping, which is really a preview for the Fifth or the Capstone, where we’re just going to do analysis, visualization and scraping. So, welcome to course Four, I hope you enjoy it.

Video: Unicode Characters and Strings

Summary of the Text about Character Encoding and Unicode

This text explains the evolution of character encoding and how Unicode addresses the challenges of representing different languages and characters in computers. Here are the key points:

Early days:

  • Computers used to have limited character sets like ASCII, which only supported 128 characters.
  • Each character was assigned a number (ordinal) for representation.
  • This limited the representation of languages beyond English.

Challenges:

  • Different character sets existed for different languages, leading to incompatibility issues.
  • Representing more characters required more bits per character, impacting storage efficiency.

Unicode:

  • Unicode is a universal character encoding standard that supports millions of characters from various languages.
  • It uses variable-length encoding (UTF-8, UTF-16, UTF-32) to represent characters efficiently.
  • UTF-8 is the most widely used and recommended encoding due to its compatibility and efficiency.

Python and Character Encoding:

  • Python 2 had separate string types for regular strings and Unicode strings.
  • Python 3 unifies strings as Unicode internally, simplifying character handling.
  • However, dealing with external data (network, files) requires encoding/decoding operations.
  • decode converts bytes to Unicode strings, while encode converts Unicode strings to bytes.

Key Takeaways:

  • Unicode is the standard for representing a vast range of characters in computers.
  • Python 3 simplifies internal character handling with unified Unicode strings.
  • Encoding/decoding is crucial for handling external data with different character sets.

So we started this entire course printing
hello world and I just said quote, hello world, quote and
out comes hello world. And it’d be nice if that was super simple. And you know in 1970,
it was simple because there was pretty much one character set. Even in 1970, when I started we didn’t
even have lowercase characters, we just had uppercase characters. And I’ll tell you we were happy when
we just had uppercase characters. You kids these days with your
lowercase characters and numbers and slashes and stuff. So the problem that computers have
is they have to come up with a way, I mean, computers don’t
understand letters, actually. What computers understand is numbers,
and so we had to come up with a mapping
between letters and numbers. And so we came up with a mapping, and
there’s been many mappings historically. The one that sort of is
the most common mapping of the 1980s is this mapping called ASCII. The American Standard Code for
Information Interchange. And it says basically,
this number equals this letter. So for example, the number for hello world, that for
capital H the number is 72. Somebody just decided that
the capital H was going to be 72. Lowercase e, the number is 101. And newline is 10. So if you were really and
truly going to look at what was going on inside the computer,
it’s storing these as numbers. But the problem is,
is there are 128 of these. Which means that you can’t put every
character into a 0 through 128. And so, in the early days we just kind of dealt
with whatever characters were possible. Like I said, when I started
you could only do uppercase. You couldn’t even do lowercase, and so there is this function, as long as
you’re dealing with simple values. That you can say hey, what is the
actual value for the letter H. And it’s called ord,
which stands for ordinal. What’s the ordinal? What is the number corresponding to H,
and that’s 72. What’s the number corresponding
to lowercase e? It’s 101. And what’s the number corresponding
to newline? And that is a 10. Remember, newline is a single character. This also kind of explains why
the lowercase letters are all greater than the uppercase letters,
because they’re ordinal for ASCII. Now, there’s so
many character sets but just for the default old school 128 characters
that we could represent with ASCII, the uppercase letters had a lower
ordinal than lowercase letters. So, Hi is less than zzz all lowercase, and that’s because
all lowercase letters are less. I mean all uppercase letters
are less than all lowercase letters. Actually this can be AAA, that’s what
I should have said there, okay? So don’t worry about that. Just know that they are all numbers. And in the early days, life was simple. We would store every character
in a byte of memory, otherwise known as eight bits of memory. It’s the same thing when you say I
have a many gigabyte USB stick, that’s a 16 gigabyte USB stick, that means there
are 16 billion bytes of memory on there. Which means we could put 16 million
characters on here in the old days, okay? So the problem is in
the old days we just had so few characters that we could
put one character in a byte. And so the ord function tells us the
numeric value of a simple ASCII character. And so like I said,
if you take a look at this the e is 101 and the H, capital H is 72. And then the newline which is
here at the line feed which is 10. Now we could represent these in
hexadecimal which is base 16 or octal which is base 8. Or actual binary which is what’s really
going on which is nothing but 0’s and 1’s. But this is the binary for 10. 0001010, and so these three are just
alternate versions of these numbers. The numbers go up to 127, if you look
at the binary, you can see in this, this is actually seven bits of binary. You could see that’s all 1’s, so
it starts at all 0’s goes to all 1’s. And so it’s like 0’s and
1’s are what the computers always do. And if you go all the way back to
the hardware the little wires and stuff, the wires are character
are taking 0’s and 1’s. So this is what we did and in the 60s and 70s we just said whatever we’re capable
of squeezing in we’re just totally happy. We’re not going to have
anything tricky and like I said halfway early in my undergraduate career
I started to see lowercase letters. I’m like that’s really beautiful,
lowercase letters. Now, the real world is nothing like this. There are all kinds of characters. And they had to come up with a scheme
by which we could map these characters. And for a while there were a whole bunch
of incompatible ways to represent characters other than these ASCII,
also known as Latin character sets. Also known as Arabic character sets. These other character sets just completely
invented their own way of representing. And so you had these situations where
Japanese computers pretty much couldn’t talk to American computers or
European computers at all. I mean, the Japanese computers just had
their own way of representing characters. And the American computers had their
own way of representing characters and they just couldn’t talk. But they invented this
thing called Unicode. And so Unicode is this universal code for
hundreds of millions of different characters and
hundreds of different character sets. So that instead of saying sorry, you don’t fit with your language
from some South Sea island, it’s okay.
We’ve got space in Unicode for that. And so Unicode has lots and
lots of characters, not 128. Lots and lots of characters. And so there was a time,
like I said in the 70s and the 80s where everyone
had something different. And even like in the early 2000s,
what happened was that as the Internet came out it became an important issue
to have a way to exchange data. And so we kind of had to say oh, well,
it’s not sufficient for Japanese computers to talk
to Japanese computers and American computers to talk to
American computers, we want Japanese and American computers to exchange data. So they built these character sets,
and so there is Unicode, which is sort of this abstraction of
all the different possible characters. And there are different ways of
representing them inside of computers. And so there’s a couple of simple things
that you might think are good ideas that turn out to be not such good ideas,
although they’re used. So the first thing we did is
these UTF-16, UTF-32 and UTF-8 are basically ways of representing
a larger set of characters. Now the gigantic one is 32 bits,
which is 4 bytes. It’s 4 times as much data for
a single character. And so that’s quite a lot of data, so you’re dividing the number
of characters by four. So if this is 16 GB, it can only handle
4 billion characters, or something. Divided by four, right,
four bytes per character. And so that’s not so efficient. And then, there’s a compromise
like I have two bytes, but then you’d have to pick. This can do all the characters. This can do sort of
lots of character sets. But turns out that even though you might
instinctively think that UTF-32 is better than UTF-16 and
UTF-8 is the worst? It turns out that UTF-8 is the best. So UTF-8 basically says,
it’s either going to be one, two, three or four characters and there’s little marks
that tell it when to go from one to four. The nice thing about it is that
UTF overlaps with ASCII, right? And so if the only characters you’re
putting in are the original ASCII or Latin I character set, then UTF-8 and
ASCII are literally the same thing. And then use a special character that’s
not part of ASCII to indicate flipping from one-byte characters
to two-byte characters or three-byte characters or four-byte. So it’s a variable length. And so you can automatically detect, you
can just be reading through a string and say, whoa I just saw this
weird marker character. I must be in UTF-8. And then if I’m in UTF-8 then I
can sort of expand this and find, represent all those character sets and all
those characters in those character sets. And so what happened was is they
went through all these things and as you can see from this graph, the graph
doesn’t really say much other than the fact that UTF-8 is awesome and
getting awesomer. And every other way of representing
data is becoming less awesome, right? And this is 2012, so
that’s a long time ago. So this was like, UTF-8 rocks, and that’s really because, as soon as these
ideas came out, it was really clear that UTF-8 is the best practice for
encoding data moving between systems. And that’s why we’re talking
about this right now. Finally, with this network we’re doing
sockets we’re moving data between systems. So your American computer might be
talking to a computer in Japan and you’ve got to know what character
set’s coming out, right? And you might be getting Japanese
characters even though everything I’ve shown you is non-Japanese characters or
Asian characters or whatever, right? So UTF-8 turns out to be the best practice if you’re moving a file
between two systems. Or if you’re moving network data
between two systems we recommend, the world recommends UTF-8, okay? So if you think about your computer,
inside your computer, the strings that are inside,
your Python like x equals hello world, we don’t really care what their syntax is. And if there’s a file usually
the Python running on the computer and the file had the same character set.
They might be UTF-8 inside Python. It might be UTF-8 inside,
but we don’t care. You open a file, and that’s why we didn’t have to talk
about this when we were opening files. Even though you might some day
encounter a file that’s different than your normal character set,
it’s rare, okay? So files are inside the computer. Strings are inside the computer. But network connections are not inside
the computer and when we get to databases we’re going to see they’re not
inside of the computer either. And so this is also something that’s
changed from Python 2 to Python 3. It was actually a big deal, a big thing. And most people think it’s great,
I actually think it’s great. Some people are grumpy about it, but I think those people just
are people that fear change. So, there were two kinds
of strings in Python, there were a normal old string and
a Unicode string. And so you could see that Python 2 would
be able to make a string constant, and that’s type string, and it would it make
a Unicode by prefixing u before the quote. And that’s a separate kind of thing,
and then you had to convert back and forth, between Unicode and strings. What we’ve done in Python 3 is
this is a regular string and this is Unicode string, but
you’ll notice they’re both strings. So it means that inside of the world
of Python, if we’re pulling stuff in, you might have to convert it. But inside Python everything is Unicode. You don’t have to worry about it, every string is kind of the same
whether it has Asian characters or Latin characters or Spanish characters or
French characters, it’s just fine. So this simplifies this, but then there’s certain things that we’re
going to have to be responsible for. So the one kind of string that
we sort of haven’t used yet but becomes important. and it’s
present in both Python 2 and Python 3. Remember how I said in the old days a
character and a byte were the same thing? And so there’s always been
a thing like a byte string and they do this by prefixing the b. And that says, this is a string of
bytes that mean this character. And if you look at the byte
string in Python 2, and then you look at a regular string
in Python 2, they’re both type string. The bytes are the same as string,
and the Unicode is different. So these two are the same in Python 2,
and these two are different in Python 2. Not doing a very good picture of that. So the byte string and
the regular string are the same. And the regular string and
the Unicode string are different. So what happened is in Python
3 the regular string and the Unicode string are the same. And now the byte string and
the regular string are different, okay? So bytes turns out to be raw, unencoded, that might be UTF-8, might
be UTF-16, it might be ASCII. We don’t know what it is,
we don’t know what its encoding is. So it turns out that this is the thing we
have to manage when we’re dealing with data from the outside. So in Python 3 all the strings
internally are Unicode. Not UTF-8, not UTF-16, not UTF-32, and if you just open a file,
it pretty much usually works. If you talk to a network now,
we have to understand. Now the key thing is we
have to decode this stuff. We have to realize what is the character
set of the stuff we’re pulling in. Now the beauty is, is because 99% or
maybe 100% of the stuff you’re going to run across just uses UTF-8,
it turns out to be relatively simple. So, there’s this little decode operation,
so if you look at this code right here. When we talk to an external resource we
get a byte array back like the socket gives us an array of bytes
which are characters. But they need to be decoded so we know,
if it could be UTF-8, UTF-16 or ASCII. So there is this function
that’s part of byte arrays, so data.decode says figure this thing out. And the nice thing is, is you can
tell it what character set it is but by default it assumes UTF-8 or
ASCII dynamically. Because ASCII and UTF-8 are upwards
compatible with one another. So if it’s like old data, you’re probably
getting ASCII, if it’s newer data, you’re probably getting UTF-8. And literally,
it’s a law of diminishing returns, it’s very rare that you get
anything other than those two, so you almost never have to
tell it what it is, right? So you just say decode it, look at it. It might be ASCII, might be a UTF-8, but whatever it is by the time it’s
done with that it’s a string. It’s all Unicode inside of this.
And so this is bytes. And this is Unicode. So decode goes from bytes to Unicode. And you also can see, when we’re
looking at the sending of the data, we’re going to turn it into bytes. So encode takes this string and
makes it into bytes. So this is going to be bytes that
are properly encoded in UTF-8. Again, you could have put a thing here,
UTF-8, but it just assumes UTF-8. And this is all ASCII, so it actually
doesn’t do anything so, but that’s okay. And then we’re sending
the bytes out the command. So we have to send the stuff out,
then we receive it, we decode it, when we send it we encode it. Out in this real world
is where the UTF-8 is. Here we just have Unicode. And so, before we do the send and
before we receive, we have to encode and decode this stuff so that it works out and
it works out correctly. And so you can look at the documentation
for both the encode and the decode. Decode is a method in the bytes class. And it says, you can see that
the encoding we’re telling it, you can say it’s not UTF-8,
ASCII and UTF-8 are the same thing. The default is UTF-8, which is
probably all you’re ever going to use, and the same thing is true, strings can be
encoded using UTF-8 into a byte array and then we send that byte array
out to the outside world. And it sounds more complex than it is. So after all that, think of it this way. On the way out,
we have a internal string. Before we send it, we have to encode it,
and then we send it. Getting stuff back, we receive it,
it comes back as bytes. We happen to know it’s UTF-8 or we’re
letting it automatically detect UTF-8 and decode it and now we have a string. And now internally inside of
Python we can write files, we can do all kinds of stuff in and out of
stuff and it sort of works all together. It’s just that this is UTF-8 ?? This is the outside world. And so you kind of have to look at
your program and say okay, when am I talking to
the outside world? Well in this case,
it’s when I’m talking to a socket, right? I’m talking to a socket, so
I have to know enough to encode and decode as I go in and out of the socket. So it looks kind of weird when you
all of a sudden start seeing these encodes and decodes. But they actually make sense. There’s sort of like this barrier between
this outside world and our inside world. So that inside our data is all completely
consistent and we can mix strings from various sources without regard to
the character set of those strings. So now what we’re going to do is
we’re going to rewrite that program. It’s a short program, but
we’re going to make it even shorter.

Quiz: Using Encoded Data in Python 3

What is the most common Unicode encoding when moving data between systems?

What is the decimal (Base-10) numeric value for the upper case letter u0022Gu0022 in the ASCII character set?

What word does the following sequence of numbers represent in ASCII:u003cbru003e108, 105, 115, 116

How are strings stored internally in Python 3?

When reading data across the network (i.e. from a URL) in Python 3, what method must be used to convert it to the internal format used by strings?

Installing Python


Video: Windows 10: Installing Python and Writing A Program

This video provides a step-by-step guide on installing Python 3 and a text editor on Windows for beginners.

Key steps:

  1. Download Python 3:
    • Visit the official Python website (https://www.python.org/downloads/).
    • Choose the latest Python 3 version (recommended for this class).
    • During installation, ensure “Add Python 3.x to PATH” is checked.
  2. Download a text editor:
    • The video recommends Atom.io (cross-platform), but any programmer text editor works (except Notepad or TextEdit).
  3. Verify Python installation:
    • Open the command prompt.
    • Type python and press Enter. If Python is installed correctly, you’ll see the Python interpreter prompt.
  4. Create a Python file:
    • Use your text editor to create a new file (e.g., first.py) and write Python code.
    • Save the file in a desired location (e.g., C:UsersusernameDesktoppy4e).
  5. Run the Python file:
    • Open the command prompt and navigate to the directory containing your Python file using cd.
    • Type python first.py (or just first.py if Windows file associations are set) to execute the code.

Additional notes:

  • The video mentions that Windows hides file extensions by default. You can change this setting for better clarity.
  • The video only covers Windows installation. The process differs slightly for macOS and Linux.

Hello and welcome to my video
that shows how to get started and install Python on Microsoft Windows. Okay, so it’s not too hard. We’re going to both install Python 3 and
we’re going to install text editor. And so I’m just going to go into Google
and I’m going to say, install Python 3. And my top link is Downloading Python. And there is my link for
downloading Python 3.5.2. This version of my class uses Python 3. I have an earlier class that you
may have seen that uses Python 2. But in this class, we’re going to do this. Now it might take you
a while to download this. I’ve actually already downloaded it. Now the other thing we need
is a programmer text editor. And you can really use any
programmer text editor. We’ve used Notepad+ in the past. We’ve used JEdit in the past. I liked Atom.io. T-O-M. .Io mostly because it works the same
on Windows and Mac and Linux. But you can really use any
text header that you like, just don’t use Word or TextEdit that
comes with the operating system. You need a programming editor that
doesn’t mess with weird characters or weird lines or strange formats

You must have a real programmer editor. And so I’m going to down,
I’ve already downloaded this as well. And so I won’t waste the time waiting
to download it but let’s go ahead and do the installation. So these things ended up
in my Downloads file, so I’ll go to Downloads. And I’ll start installing Python 3.5.2. Now it’s going to ask me some things. Add Python 3.5 to the path. Yeah, that’s a good idea. Install the launcher for all users. I’m going to add that. Maybe you will, maybe you won’t do that. It’s going to tell me where
it’s going to install it. Install Now. [SOUND] Of course, it’s going to ask
me for permission to do these things. And now it’s running
through the installation. Okay, so there we go. You could maybe click on this online
tutorial and documentation, but we’re just going to close this. And I’m going to start and
run the Windows command line. Now, you may have all kinds of
fancy ways to run Python but I like running the command line. C-O-M-M-A-N-D.
I like running the command line because after a while it’s important to know what folder things are being run in. and so here’s this command line and
I should be able to type Python here. And so now I’m in Python 3.2 and
this is the chevron prompt. Here is the Python interpreter where
it’s asking for Python commands and I can say print. Hello world, of course this is what
we tend to print all the time. I can make a mistake, I can say. Right, and it’ll complain to me. Now, to get out of this,
I can either type Ctrl+Z or quit. In this case, I’m going to type Ctrl+Z,
and I’m back to the prompt. A couple of things,
I can do a dir to see what folders and files I have, and that is like my desktop. And then the cd command tells
me where I’m at in the folder, that means I’m in the user’s
directory doctor chart, okay? So I have now installed Python. I ran the Python interpreter to verify it. I said, print Hello World. Okay, and so now what I’m going to do
is I’m going to actually install Atom. And I already had this downloaded,
so let’s go ahead and install Atom on my computer. Okay, so Atom is now installed and
it’s kind of telling us what to do. I’m going to actually just close all
these windows, close this window, close everything, and
I’m going to create a file. I’m going to say print, in this case, let’s see if I can make this bigger, I can make it bigger, so
I’m going to type print, hello from a file, okay,
and I’m going to save this. I’m going to say File, Save as, and what I’m going to do is
I’m going to go to my desktop, And I am going to make
a folder on the desktop. I’m going to call this folder py4e. So I now have a folder on the desktop. Move this here and move this here. Oops.
And I’m going to go into py4e and then I’m going to name this file first.py. And you’ll notice that when I save this, it’s syntax highlighted it. That’s one of the nice things
about a programmer editor. Okay?
And so it says, it’s got a suffix of .py. So therefore it knows that it’s
supposed to look pretty with Python and make this one color,
make this another color. The other thing that you’ll notice is
that I now have a folder called py4e. And if I’m in this command line,
let me just start that up again. I’ll show you how to start
the command line again. Command, now if I do a dir,
I see the folders that I’m in. And one of the folders that you can
see here is the desktop folder. So I’m going to say cd.desktop, and then I’m going to type the dir command
to see what folders are in the desktop. These folders are the same
as these folders. This things are kind of virtual folders. Py4e is py4e. Now I can type cd, which stands for change
directory, py4e and I can do a dir and now you see first.py and that’s the same
as if I’m diving into this folder. Here’s this file, first.py, Windows hides
the suffix, which is somewhat annoying and frustrating, but that suffix is there,
that file is there. And so for me, one of the things you gotta
figure out in Windows is how to make sure you are in the same folder,
UsersdrchuDesktoppy4e, and that’s the name of this file,
and here as well. And now I’m going to run this program. I’m going to type python first.py. And you see that it ran the Python code. Okay? Another way you can do this
is you could type first.py. And that’s because this file
association has happened in Windows. This doesn’t work in Macintosh. This only works in Windows, that all
files with .py are expected to be Python. And it knows the Python
interpreter where to run it. Okay, and so I’ve got Python 3.0
installed and that gets me started and so I hope that this little introduction
about getting things started and writing your first Python
program has been helpful to you.

Video: Windows: Taking Screen Shots

Snipping Tool Tutorial Summary:

This video demonstrates how to use the Snipping Tool on Windows 8 to capture screenshots.

Key points:

  • Open the Snipping Tool by searching for “Snipping Tool” in the Start menu.
  • Select the desired capture mode (e.g., Window Snip, Freeform Snip).
  • Click and drag to capture the desired area of the screen.
  • Edit the screenshot (optional) using tools like pen and highlighter.
  • Save the screenshot as a PNG or JPG file.

Additional tips:

  • Use keyboard shortcuts for faster access (e.g., Windows Key + Shift + S).
  • Specify a default save location for convenience.
  • Explore advanced options for more precise captures.

Overall, the Snipping Tool is a simple and effective way to capture screenshots on Windows.

Hello, and
I would like to talk to you about how to use the snipping tool
to do a screen capture. There are other ways to do this, but the
easiest way is the built in screen tool, and I’m doing this on Windows 8. The snipping tool exists on earlier
versions Windows as well, and so the gestures and the UI might look a
little different but it is about the same. You find the snipping tool. So, I’m going to hit the Windows icon, and I’m going to type S-N, and
it brings up the Snipping Tool. And so, here I go. And, it’s giving me this
option to say Snipping Tool. And, I like to say,
I’m going to do a new Window Snip. An now,
it’s kind of graying out the screen and following me around with
this little red line. And I clicked on this and
it has made a copy of that window. Now this Snipping Tool is just
Snipping Tool, that window still exists. This is now, didn’t want to do that. This is now just a drawing tool that’s. So, and so here you are. We could save this, but
the other thing you can do and this is in the more recent snipping
tools is you can make changes. So let’s say for example that you
didn’t want to show your name, and your name was in this path. And so I will just go and scribble my name out,
like with this little scribbling tool. Pretty sweet? So, I scribbled my name out. I just happened to have my name in it,
so I just didn’t want to put it in. So now, I’m going to do File > Save as. And, of course, find somewhere,
I’m going to put this on my Desktop, and I’m going to call it notepad.png. Now, you don’t have to put
a suffix of .png or .jpg. But it’s good if you’re
moving files between systems. So, put the suffixes on. Windows would know this was a PNG file,
but .png is a way to nicely tell other systems, when you’re moving it around,
that it’s a PNG file. Or, if you send it as an email,
or whatever. So, I save it, I’m saving it on
my desktop, and there we go. So it’s hiding the .png, but I can look
to make sure the png is really there. And so there it is, it’s a .png. And so there’s a file and
away we go, okay? So there’s the snipping tool. If I close this window and
I click on Notepad, [SOUND] you will see that it’s
got the little scribbling thing. Thank you for that, okay? So, there you go. That’s how to do a real
simple snipping tool.

Video: Macintosh: Using Python and Writing A Program

Summary: Installing Python 3 on macOS

This video guides you through installing Python 3 on a Macintosh computer even though it comes pre-installed with Python 2.

Why Install Python 3?

  • While macOS comes with Python 2, many modern libraries and programs require Python 3.
  • Python 2 is nearing the end of its support, making Python 3 the recommended version.

Downloading and Installation Steps:

  1. Visit the official Python downloads page: https://www.python.org/downloads/windows/
  2. Download the latest Python 3 installer for macOS.
  3. Run the downloaded installer and follow the on-screen instructions. This typically involves clicking “Continue” and agreeing to the license agreement.

Verifying Installation:

  1. Open a terminal window (Applications > Utilities > Terminal).
  2. Type python3 --version and press Enter. If Python 3 is installed correctly, you’ll see the installed version displayed.

Running your first Python program:

  1. Use a text editor like Atom (https://atom-editor.cc/) to create a new file.
  2. Write your Python code (e.g., “print(‘Hello, world!’)”).
  3. Save the file with a .py extension (e.g., hello.py).
  4. Navigate to the file’s location in the Terminal.
  5. Run the program with the command python3 hello.py.

Important Notes:

  • Use python3 to run Python 3 scripts. Using python alone might still run Python 2 if available.
  • This guide recommends learning the command line for better understanding of Python execution.

Additional Resources:

  • The video mentions the Atom editor (https://atom-editor.cc/) as a good option for beginners due to its cross-platform compatibility and syntax highlighting.

In this video, we’re going to actually download and install Python 3 from python.org on a Macintosh if your Mackintosh, for years, has wonderfully come with Python 2. So, if I type Python minus minus version, I type that, I see that I’m got Python 2.0. What we want to do is in addition installed Python 3. One of these days, Macintosh might upgrade their distributed version of Python 3, but there’s so many things inside Mac that depend on Python 2. I’m going to expect that it will always be named Python 3, which is what we’re going to call it in a second. So, here I am at the python.org/downloads, and I’m going to download Python 3, you click here, and I’m actually got it sitting here in Downloads already because I always do that. So, I’m going to install this. There is the installer, we’ll say Continue, Continue, Continue. Of course, I agree. I read all that really fast, and now I’m going to install it. Okay. So now, that means if I run a terminal, so this of course, is start run terminal. So, Python 2 is still there, but Python 3 is also now involved there. So, we should have Python 3 installed. So, we install Python 3.6, and so there we go. That’s all it takes to install Python 3 on a Macintosh. So, let’s write our first little Python program. I’m going to, I like Atom. So, I’ve got this Atom Editor, it’s atom.io. Right here, atom.io, download and install the Atom Editor. I like it because Atom works the same on both Windows, Mac, and Linux, and it has syntax highlighting, so I really like things like that. So, I’m going to make myself a simple Python program. Hello world, like we always do. Now, you’ll notice that it’s not syntax highlighting yet, but I’m going to do a File, Save As, and I’m going to go into my desktop, and I want to make a folder called py4e. I’m just calling this call as hello.py. Oh, crud got to rename it. Rename it, and put two dots hello.py, there we are. So, now I’m here, and I’m in my home folder, I can go on my desktop, and I can go into that new folder I made Python for everybody, and I can see the files. Now, there are ways to run this. I really want you to learn the terminal so that you really know what you’re doing. So, here we are, we’re in the folder that has the Python, and then all we do to run it is we say, “python3 hello.py”, and there we go. Of course, this is Python 3, because I’m using parentheses there instead of double quotes. But Python two is still there, and of course, if you just run python hello.py, it’ll be a syntax error or not. Must be they added something. Yeah. Because Python is still version two, but apparently, they allowed print in the latest version of Python 2. So, away we go. Okay? So again, thanks for watching. I hope this was helpful to you to get Python 3 installed on your Macintosh.

Video: Macintosh: Taking Screen Shots

Taking Screenshots on macOS with Preview:

This guide explains how to take screenshots on a Mac using the built-in Preview application:

1. Accessing Preview:

  • Open the Applications folder.
  • Search for “Preview” and launch the application.
  • Alternatively, keep Preview in your Dock for easy access.

2. Capturing a Screenshot:

  • Open the window or program you want to capture.
  • Go to “File” > “Take Screenshot” in Preview.
  • Choose “Grab window” and click on the desired window to capture it.

3. Saving and Managing the Screenshot:

  • Preview saves the screenshot to your desktop with a long generic name.
  • To change the format and name, go to “File” > “Save As.”
  • Choose your preferred format (e.g., JPEG) and give it a descriptive name.

4. Additional Tips:

  • Preview offers a cropping tool to remove unwanted parts of the image.
  • Select the area you want to keep, go to “Tools” > “Crop,” and save the cropped version.
  • Regularly clean up old screenshots from your desktop to avoid clutter.

5. Uploading Screenshots:

  • When submitting a screenshot, upload the saved file with your preferred format and name.

Overall, Preview provides a simple and effective way to capture and manage screenshots on your Mac.

Hello, and welcome to the podcast on
taking screenshots on the Macintosh. Nicely, the Macintosh has
a very simple tool built in. We go into Macintosh hard drives,
we go to Applications, and then we search down for Preview. Preview, right here. So Preview.
And I’ll close this now. So we’ve got Preview. Preview’s the application that was
originally built to view PDFs on the Macintosh. But it also has a whole series
of screen capture capabilities. And I like to keep Preview
in my dock all the time. So I come down here on the Preview icon. And it’s already in my dock. If I said remove from dock, and
then I would say keep in dock. It was already there, as soon as I start
Preview, I always keep it in the dock. But all the things I need to
use all the time in the dock. And so, let’s take a screenshot. I’ll just sort of start a jEdit program. And I’ll say take me as a screenshot. Whatever. Doesn’t matter. Just this is the window that
I want to take a picture of. This window right here. So I go to Preview, and I say File. This is in the most logical place. Begin to grab a rectangular
selection in which you’ll be allowed to draw with your cursor or a window or
the whole screen when timed. 90% of the time, what you really
want to do is take a window. You can say grab window, it tells you
you can grab, go over different windows, I can click here, I can click there,
I can click there. And I just want to capture this windows. So click, I go like that. Now, here is a little weird. This is now on image, okay? And so,
you can’t click on this stuff, okay? That’s that. So what you need to do. I’m going to close
the original real window now. This is my J Edit,
I’m going to Cmd+Q get rid of J Edit. And I do not want to save that file. So now, I’m in Preview. See, I’m in Preview here. And so, I’ve got this as an image. Now, the one thing it does is it
always saves it to your desktop. So which gets to be sort of
painful after a while. It gives them these long names called
Snapshot that has the date, and stores it in this format capped Tip. So I prefer to switch it
to a non-Apple format. So I want to do a Save As. And I’m going to save this as a JPEG. And I give it a better
name called first image. And it’ll be a JPEG, and
I’m going to store it right on my desktop. So now, here we have first image, okay? And I can click on that and
take a look at it. I’ll close this. Click on it. Interestingly, it just
comes back up in preview. So that’s pretty much it. This would be the file you would
upload if your job was to do this. I’ll show you a couple other tricks I like
to make my images a little bit better. Preview has a simple tool for cropping. And the way you crop something is you say, you draw a rectangle here on the image,
and then you say Tools > Crop. And now, I’ve gotten rid of all the rest
of that image except that which I want. And I’ll say save this as,
I want to save it as a JPEG tiny. And so, I now have two images, I got
that first image and this tiny image. And there it is. I’ll use Apple+W to quickly close it. And so, the one thing is is you just,
after a while, these snapshots fill up on your desk,
and so just keep cleaning them off. And if you were uploading
to hand in a screenshot or whatever, this would be
the filet that you upload. So that’s pretty much all there is. Use the preview command to take
screenshots with the grab. And typically, it’s grab window, okay? Thanks.

Lectures


Video: 14.1 – Object Oriented Definitions and Terminology

Demystifying Object-Oriented Programming in Python: A Gentle Introduction

This chapter embarks on a journey into the realm of object-oriented programming (OOP) in Python. While OOP may seem complex at first, this chapter aims to provide a foundation for understanding its core concepts by gradually introducing key terminology and exploring its practical applications.

A Glimpse into OOP Fundamentals:

  • Classes: The blueprints or templates that define the characteristics and behavior of objects. They serve as the foundation for creating objects that share similar properties and functionalities.
  • Objects: Instances of classes that encapsulate data (attributes) and functionalities (methods). They represent real-world entities or concepts with specific attributes and behaviors.
  • Methods: Functions defined within a class that operate on the object’s data, allowing objects to perform actions and interact with the world.
  • Attributes: Data elements or properties associated with an object, representing its characteristics and state.

Unveiling the Power of Abstraction:

The chapter emphasizes the concept of abstraction, a core principle in OOP. By encapsulating data and functionalities within objects, OOP promotes code modularity, reusability, and maintainability. This separation of concerns allows developers to focus on the “what” (functionality) without delving into the intricate details of “how” (implementation) things work.

Learning Through Analogy:

To enhance comprehension, the chapter employs relatable analogies. Classes are likened to cookie cutters, defining the shape and characteristics of objects (cookies) that are subsequently created from them. Similarly, the concept of blueprints is used to illustrate how classes serve as templates for constructing objects with specific attributes and behaviors.

Exploring Built-in Features:

The chapter briefly mentions the dir() function, a built-in Python tool that introspects objects and classes, revealing their available methods and attributes. This functionality aids developers in exploring object capabilities and fostering a deeper understanding of object-oriented design principles.

The Road Ahead:

By laying the groundwork with these fundamental concepts, the chapter prepares learners for the exciting task of creating their own classes in the subsequent section. This hands-on experience will solidify their understanding of OOP principles and empower them to leverage the power of object-oriented programming in their Python endeavors.

This refined summary presents the core concepts in a professional and concise manner, suitable for a wider audience, and avoids informal expressions while maintaining clarity.

Hello, welcome to the
chapter on Python objects. This chapter is, in a sense, a little different
than Chapters 1-10 in that learning
object-oriented programming for me is like a lifetime
and I’m not going to, in this next lecture, teach you everything
that I ever want to teach you about
object-oriented programming. It’s so beautiful and
so deep and so complex. What this is really about is getting you used to
hearing the words that were used to talk about object-oriented programming
and getting you to freak out less about these words and over time and over
multiple courses, these words will grow
in terms of meaning. I don’t think I can
in this one set of lectures just put
all the meaning to it because you just can’t. You can relax a little bit and you can enjoy this lecture. We’re going to talk
about some syntax, so there’s going to
be some Python code, but what I’m saying is this is something that
you’re supposed to absorb rather than really get because the really getting
is a much longer process. The first thing that
we’ll notice is if you look at any
documentation, the word object has
already been in there. This is like some list
documentation and it says here are some
methods of list object. The list data type
has some methods. Well, what’s this word object and what’s this word method? Now to some degree, you don’t have to know what
this means because you say list out a
pen I’ve showed you a code that uses list
out a pen all along. What’s this dot? Well, the dot is the
syntax that says here is an object or a class and then a thing within it,
that’s what the dot is. The append is inside the list
object or the list class. Now we’re just going
to add something to the terminology of this. Syntax is easy and you can sort it on stack,
overflow, copy-paste, or whatever but now we’re going to learn
about the terms and what these terms mean. Again, you keep looking
at the documentation, the word object, and
we do databases. The connection object, well, the key thing is if
you’ve got an object, you should expect that
there are things like attributes and methods
inside that object, and so call it it’s
execute method, the method to perform. Again, the first thing I want you to do is be able
to read this documentation and when you see the
word object and you see the word method and you
see the word attribute, you don’t go, huh? Let’s start to talk about object orientation because
one of the things about object orientation
is a concept we call abstraction and that is there’s stuff that’s
inside something, the implementation, and then
there’s the outside world. Let’s start talking
about programs. If you think of this program as an object of the boundary of what’s inside of it and
what’s outside of it. The inside is some three
lines of code that we’ve seen before where
we read a variable, we convert it to an
integer, we add one to it, and we print that
out and that you could think of as like a
gadget that you bought, the floor converter gadget, and you just talk to it and say, what is the United
States floor if the European floor is
three and it goes four. That’s a gadget. The inside
of it is this logic, and the outside of it is what we give it and what we
get back from it. You wouldn’t need to know if you had this floor
conversion gadget, you wouldn’t need to know it’s
Python it doesn’t matter. It could be using
artificial intelligence for all you know but it doesn’t matter because we have this abstract object that
does something for us. Again, this one, of
course, is super simple. If then we start looking
not just from the program, but within a program, a program is made up of many cooperating objects and this whole notion of
there’s the inside and the outside that
happens over and over again like a series
of onions and it works its way all the way down. When you have three
strings in your program, you have like three
little islands of capability and each of the
strings has some data in it, it has some methods, etc and so you can think of what you’ve been doing
as you write programs. You are orchestrating
multiple objects. You’re taking something
out of one object, putting it in another one, or you’re putting an object
inside of another object, like a dictionary or a list. You’re like, here’s a string and I’m going to put it in a list. Well, the string is an object
and the list is an object. You’re the orchestrator
of all these. Your program is like
lots of objects working together in ways that
you are constructing, and objects interact
with each other all the time under your control. What is an object? I keep saying this word, it’s
a bit of self contained. Again, there’s an outside,
and inside that’s a self contained bit of data. Inside of the inside, there’s code in it and
there’s data in it. A key aspect of object in a
programming is in order for you to not have to look at the complexity of what a
string object is really doing. If you were to go on
to Github and look at the source code of Python and
look at the string object, it’s probably 2,500
lines of code. How hard is it to make a string? The answer is, for us in
Python, it’s really easy. But under the covers, the work to make a string
work is 2,500 lines of code, or probably even more. But the idea is that object
in programming says, let’s make a thing
that’s easy to use and not be forced to understand
what’s going on inside. Someone can be an expert, and they’re in the Python world, there probably is 10 people who are expert in what’s
inside the string object, and we don’t care
because we have a nice interface
between us and them, so we can ignore
unneeded detail. Like I said, we have been
using objects all along. String objects.
Integers are objects. They’re dictionary
objects, list object. Some are tiny and some are big, some are collections, some are simple scalar things. We’ve used them all along. If we look at that program, send some data to it, that data goes into
a string object, and then we might use a dictionary and we might
produce another object, and we might print
that string out, and so you can see the
code that you’re doing, even though you’re
just writing Python, you’re orchestrating objects, and then each of
those objects has a bit of code and a bit of data, and that’s on the inside. You get to not worry
so much about that, but the person who’s writing the string class or the
dictionary class worries a lot about the
code and the data that’s inside each object, but it goes both ways. The person who’s
writing the string or dictionary class can ignore
what your program is doing. Because they’re looking outward
from this little bubble. They’re looking outward
and they’re like, I’m going to let you do this, I’m going to let you
do an upper case, I’m going to let you
reverse the string, and I got to write
all that code. But look, I don’t
care how you do that. You can reverse it if you want. I don’t care if you
do reverse or not. So the object creators are giving capabilities to
us that we then use, but we don’t have to look
at what they’re doing and they don’t have to look
at what we’re doing. We can not care about how difficult the string
object was to implement. Again, it has to
do with creating boundaries and not having detail pass across
those boundaries, and having well defined rules, we call them interfaces. Well defined rules for what the string object
is supposed to do. Over the years in Python, the string object has
gotten better and better. Faster, better with
memory, more efficient. Someone did a PhD thesis on how to do strings
better in Python, and then they put
it in a Python, and narco didn’t change
at all because we don’t care what’s going
on inside that thing. Because of how object oriented programming isolates things, and that allows them to
be beautiful and complex, rich, powerful, and
then easy to use. Here’s some definitions. A class is the actual code that defines how an object
is going to behave. But it’s not the object itself. You could think of it in my little picture of a
cookie and a cookie cutter. The class, a cookie
cutter is not a cookie, but you can use
the cookie cutter to make lots of cookies. The cookies are
objects or instances. We use these two names depending on what book people read
or whatever it might be. When everyone says class
and then they might say, oh, I made a real cookie. That’s a cookie object
or a cookie instance. It’s a particular instance. I like instance, but most everybody just
calls them objects. Then within that, there
is every class defines a set of fields and attributes and then methods or messages, and again, there’s two kind of cultural terminologies
that are equivalent. The method is I either call
some code inside the class, or I send a message to
the class which activates some code inside the class
which is the same thing. Or I’m like, I want to pull
something out of the class, just some data out
like how long is the thing or is it active yet, that’s like a field
or an attribute. Again, don’t be concerned
about the fact that you hear this terminology
two different ways. Class and object are probably the hardest parts to understand. The class defines the abstract
characteristics of a thing. It’s not the thing itself. It’s the pattern
or the template. It’s like when this
thing is created, it’s going to have
these attributes, these fields, these
properties, these methods. You might say it’s
like a blueprint, but it’s not a building. That’s a class. An instance is
when you make one, you use the template
and then you construct a thing out of cookie dough
or perhaps out of wood. Here’s a blueprint
for a building, and I bring a bunch of wood and pound it
together according to the blueprint and now I have an instance of a building. Literally, if you
have a blueprint for a building and you go next door and you want to
build the same building, you just bring more wood
and make another building. The instance or object is the thing that
actually stores the data. It’s the thing that
you interact with. You generally don’t
interact with the class, except at the moment
that an instance is created from the class and
you interact with that, the class is defining
all the behaviors. The code we write
when we write this, and you’ll see this in a bit, we write the class, then we make objects
and use the objects. But really the code
is in the class. I told you it’s going
to take a while to get all this right. It’s simple and beautiful
once you get it. A method is in the class, but it’s also in each
instance or object. The method is telling
it to do something like string upper
case, string, reverse. Do something. It’s like a verb. The method and message are
often used interchangeably. Like I said, the method is
like I’m going to call. I like method more
than message in this case because I think of
it as if I write my class, I put code in the class and then I activate the method
which calls that code. I like method better
than message. Object pures message better because the message focuses
on the interaction. A string object sends a message to the
dictionary object and it’s the picture
with all the arrows. I get why they like message, but for me I just want to see the code
and think of the code. For me I’m more of a,
that line of code, calls that line of code
and that’s a method. That’s why I like method better. You can use the built in
capability in Python called dir. We’ve been talking
about type like, what thing is this? Well, it’s a string thing
or it’s a floating thing, or an integer thing, or
a list or a dictionary. That’s just the class that was used to construct that thing. You see the word class there. It’s a str class,
it’s a float class, it’s an int class,
it’s a list class, it’s a dict class. But then you want to say, well, what are the methods
and attributes? There is a function
called dir and you can pass an instance which is
like x or even a class n, and it says these are
the capabilities. It’s a pretty weak way to read the documentation when you could go read the documentation. But I sometimes use it. Is there two L’s
in that or one L? My problem is I go
back and forth between languages like is it
L strip or L trim? Because some of the languages, the concept of strip is trim. I’m sitting in Python and
I’m like string.trim. It’s like, no,
that’s PHP, I think. See, I can’t use
too many languages. But I’m not saying the dir is a good way to look
at documentation. But it does tell you
that Python itself is self aware of the
nature of objects, and classes, and methods. It was valuable for me
to look at this and say, Python knows all this stuff. It remembers it. When you make a variable, it remembers where that
variables methods came from. Up next we’re going to actually, instead of just talking
about classes in the abstract, classes
in abstraction. We’re going to build
our own class.

Video: 14.2 – Our First Class and Object

Creating and Using Classes in Python: A Summary

This explanation outlines the concepts of classes and objects in Python, using the example of a PartyAnimal class.

Key Points:

  • Classes:
    • Blueprints for creating objects.
    • Defined using the class keyword followed by the class name.
    • Contain methods (functions) and attributes (variables) that define the object’s behavior and properties.
  • Objects:
    • Instances of classes.
    • Created using the class name followed by parentheses (e.g., PartyAnimal()).
    • Have their own attributes and can call the class’s methods.

Example: PartyAnimal Class:

Python

class PartyAnimal:
  def __init__(self):  # Special constructor method
    self.x = 0  # Attribute initialization

  def party(self):
    self.x += 1
    print("Partying!", self.x)

Explanation:

  1. The PartyAnimal class is defined with:
    • A constructor method __init__(self) that initializes the x attribute to 0.
    • A method party() that increments x and prints a message.
  2. An object an is created from the PartyAnimal class using an = PartyAnimal().
  3. Calling an.party() three times increments x and prints “Partying!” messages.

Additional Notes:

  • The dir() function lists the attributes and methods of an object.
  • Classes extend Python’s capabilities by allowing you to define custom data structures and functionalities.
  • This is a basic example, and classes can be much more complex with inheritance, encapsulation, and other features.

Further Exploration:

  • Object lifecycle (creation, destruction, and related methods)
  • Advanced class concepts like inheritance and polymorphism

Creating and Using Classes in Python: A Beginner’s Guide

Welcome to the world of object-oriented programming (OOP) in Python! This tutorial will guide you through the fundamental concepts of creating and using classes, which are the building blocks for structuring your code in a modular and reusable way.

1. What are Classes?

Imagine a blueprint for creating houses. This blueprint specifies the essential features of a house, like the number of floors, bedrooms, and windows. Similarly, in Python, a class acts as a blueprint for creating objects. An object is a specific instance of a class, like an actual house built based on the blueprint.

2. Defining a Class

Creating a class involves defining its characteristics using keywords and code blocks. Here’s the basic structure:

Python

class ClassName:
    # Class body
    
    # Methods (functions)
    def method_name(self, arguments):
        # Method implementation
        
    # Attributes (variables)
    attribute_name = value

Explanation:

  • ClassName: This is the name you choose for your class, following Python’s naming conventions (e.g., CamelCase).
  • Class body: This section contains the definition of methods and attributes that belong to the class.
  • Methods: These are functions defined within the class that operate on the object’s data. They typically take the special self parameter as the first argument, which refers to the current object itself.
  • Attributes: These are variables that store data specific to each object of the class. You can define them either inside the class body or directly within the __init__ method (explained later).

3. Creating Objects (Instantiation)

Once you’ve defined a class, you can create individual objects (instances) of that class using the following syntax:

Python

object_name = ClassName(arguments)  # Optional arguments for the constructor

This statement:

  • Creates a new object of the specified class and assigns it to the variable object_name.
  • Optionally, you can pass arguments to the constructor (the __init__ method) during object creation. These arguments will be used to initialize the object’s attributes.

4. The Constructor (__init__ method)

The constructor, denoted by the __init__ method, is a special method that gets called automatically whenever you create an object of the class. Its primary purpose is to initialize the object’s attributes with their starting values.

Here’s an example:

Python

class Dog:
    def __init__(self, name, age):  # Constructor with arguments
        self.name = name
        self.age = age

    def bark(self):
        print(f"{self.name} says woof!")  # Accessing attributes within a method

my_dog = Dog("Buddy", 3)  # Create an object and pass arguments
my_dog.bark()  # Call the bark() method on the object

In this example:

  • The Dog class defines a constructor (__init__) that takes two arguments, name and age.
  • When you create an object like my_dog = Dog("Buddy", 3), the constructor is called and assigns the provided values to the object’s attributes (self.name and self.name).
  • The bark() method demonstrates how objects can access their own attributes using the self reference.

5. Accessing and Modifying Attributes

Once an object is created, you can access and modify its attributes using the object reference variable followed by a dot (.) and the attribute name.

Python

my_dog.age = 4  # Modifying an attribute
print(f"{my_dog.name} is {my_dog.age} years old.")  # Accessing attributes

6. Additional Notes

  • Classes promote code reusability by allowing you to create multiple objects with the same characteristics and functionalities.
  • You can define additional methods within the class to perform various operations specific to the objects of that class.
  • While not covered in detail here, classes can also inherit properties and functionalities from other classes through a concept called inheritance, further enhancing code organization and reusability.

Practice and Experiment!

The best way to solidify your understanding is to practice. Try creating different classes and objects in Python, experiment with methods and attributes, and explore how they interact. This hands-on approach will equip you with the skills to effectively utilize classes in your Python programming endeavors.

Enough of me talking about
definitions. Too many words. Let’s get to writing some code. Let’s write our first
class. Here we go. Like everything, I make these things small
so that I can make them big on the screen and they don’t do anything
particularly useful. So don’t feel too
bad about like, why is doing this, because really you’re just
talking about syntax. So the first thing to notice is there is another reserved word. Def makes functions,
class makes classes. Now remember, classes
are templates. Classes are not the thing. So you say class, then you have the name of the
class that you’re creating. Much like you’d have the
name of a function and then colon and then there is a whole chunk of indented stuff. Those two defs are both methods. So methods are basically functions inside of
or scoped to class. The first function
is what we call, it’s a specially name function
and double underscore that starts and ends the
function name is a way that Python knows that
this has special meaning. It also is a way that you’re not supposed to do these unless Python has
told you to do it. Python tells you, create a double underscore init double underscore method
with a parameter of self. That’s what Python is going
to call when you are created. That’s a specially named method. Self is the actual instance, so class is a template
to make an instance. What’s going on is, in the an equals PartyAnimal
open paren for close paren. That’s the act of building an instance of
PartyAnimal and then giving it back to you
in the variable an. But then as side
effect of building it, Python is going to call
the constructor method, the double underscore
init double underscore, and is basically letting you do things in there
to set things up. We’re going to
have an attribute, in this case x, self.x = 0, that both defines an
instance variable or an instance attribute
of x and set to zero. When we’re done there,
whatever this class is, whatever the object is, has been constructed and initialized
whatever it is we want. Now again, I’m
keeping this simple. We’ve got one variable in this, one attribute in this, and it’s x and it’s set to zero. Then we have another method, and you’ll notice
that every one of these methods takes
self as parameter. Self is the particular instance. We’ll get to multiple
instances much later. If you call the party method, we take the x value within
this and add one to it, and then put a
print statement in. It’s just Python code. So you can put print
statements in here. Most methods don’t do printing, but we’re doing it just so
we can see what’s going on. At that point, we de-indent to the zero indent position
and now we’re in the main code and we say
an equals PartyAnimal. That says, hey Python, there’s a class of type
PartyAnimal that we just created. Construct it, initialize
it and give it back to us. The constructing happens,
then in our init it gets called and then it’s all set. Then we say an.party, which means we’ve
got an object now, we’ve got an instance of class PartyAnimal and we call the party
method inside of it. Now the thing you’ll
notice is inside the parentheses of
an.party is nothing. But inside the def
party there is self. Takes a little getting used to, but you can see
that the an.party syntax is equivalent to
the clunkier syntax, but perhaps easier
to understand. PartyAnimal which is the
class dot party which says there’s code inside of
PartyAnimal named party, and we’re going to
pass the instance in, the an variable which is that instance as
its first parameter. When party gets called
inside of the instance, we pass in the instance. In that moment an and self are pointing
to the same thing. We’ll get to multiple
instances later. But you get the
idea that we define the class with a method to initialize it and a method will call for whatever purpose. They both take self
as a parameter. X is the only attribute
that we have, and then an equals party
animal constructs it. Then an.party calls
the party method, and we do that three times. Let’s see how this runs. If we’re running this,
we get it started. As it goes down through
class party animal, we don’t see any output. Even though it’s at
that line where it says an equals party
animal, open print, close print, that print
statement did not run. That’s not that different than
when we create a function. If the function
has a print in it, it doesn’t run the print
until we call the function. The top two-thirds of this is defining something but
not running the code. In the middle, before we
say an equals party animal, all we have done is created this party animal
template with no output, no real execution, it’s just recorded the store
and reuse pattern. Then we get down to an
equals party animal. Then using the party
animal template, it constructs some data. In this case, the
initializer creates the x instance variable
and sets it to zero, and the whole class has
a party method in it. Now, at the end of that line, an points to an instance of a class or an object
with x and party in it. Then we go down the
next lines and we say an.party. Well,
what does that do? Well, that adds to self.x, and x is changing, and when you’re in
the party method, self in that parameter to the party method
is an alias of an, and that’s how you
get to the instance Self.x is the same as an.x, and x is the attribute
of the instance. It goes 1, 2, 3, so we call it three times, and eventually it prints
out three of them. Now that we’ve
created this class, we’ve extended Python
when we create a class. No different than when
we create a function, we extended, we’ve stored a new
thing that we invented. It’s really a Python
capability that we’ve built. It didn’t run code, it just is a capability. Now we’re going to
play a little bit with the dir command. If you recall, the dir
command lists capabilities. It really is listing methods, but it also can list
attributes as well. Remember that the ones
that have underscores, those are for Python. Underscore is saying, don’t play with this stuff unless
you’ve been told to. The underscore
underscore and knit is something you’ve
been told to do. You put that in your class. But do not try to mess with your own underscore
underscore add, or underscore underscore
del item, or whatever. But the rest of
the operations are the operations that
we can perform. Again, the double underscore
is Python signal says, don’t call this, don’t
just leave this alone. The dir is basically telling us what capabilities
are in list. Now, let’s use dir, because we made a thing. Party animal and list
are both templates, and then we can make an instance and we can ask
questions about it. Now what we’re going to
do is we’re going to define a party
animal in the top. Then an an equals party animal is going to create an instance of the class and call the initialization method and
give it back to us in an. Instead of doing
anything with it, we’re going to be like,
what kind of a thing is it? Well, it’s class underscore underscore main party animal, which is defined in the
file underscore main, which is our main program. Then you do a dir, and you see all kinds
of things are in there, including party
which is a method, and x which is an attribute. Again, this goes back to
Python is self-aware. It knows what a party animal is. You’ve extended Python
and you’re like, what kind of thing is this? It knows what kind
of thing it is, because it’s got a
template in there. It’s just reading the
template and telling you what’s in that template. Then you can say, what’s
the type of an.x? Well, that’s an
integer. Then you say, well, what is an.party? It’s like, that’s a method. It just seems to know all
this stuff about your object, just like it knows about
lists and other things. You’re like, you’re
in the system. You’re jacking into the system. You’re creating classes now. Python has a bunch of classes. You’re creating your own class. Then the trick, of course, is how you’re going to use that. Again, taking a look at
the dir with a string, you see that someone else
wrote all this code, not you, and then these are all the things that you
can do to a string. Up next, we’re going to talk
about object lifecycle. We really have
been talking about object lifecycle all along. The double underscore and knit thing, that’s object lifecycle. That’s the construction
and initialization phase. But there’s a little bit
more to object lifecycle, and we’ll talk about that
in the next section.

Video: 14.3 – Object Life Cycle

Object Lifecycle in Python: Creation, Initialization, Destruction

This summary explains the concept of object lifecycle in Python, focusing on constructors, destructors, and their roles in object creation and destruction.

Key Points:

  • Object Lifecycle: Objects are created, used, and discarded. This process is managed automatically through garbage collection.
  • Constructors (__init__ method):
    • Special code block called when an object is created.
    • Used to initialize instance variables with their initial values.
  • Destructors (__del__ method):
    • Less commonly used, but can be used for specific cleanup tasks when an object is destroyed.
    • Not typically needed unless the object manages scarce resources like database connections.
  • Example:
    • PartyAnimal class is used to demonstrate constructors and destructors.
    • The constructor initializes variables like self.x and self.name.
    • The destructor (if present) can perform actions before the object is garbage collected.
    • Assigning a new value to a variable holding an object triggers the destructor (implicitly called).

Additional points:

  • Inheritance is briefly mentioned as a way to reuse code and create new objects with additional functionalities based on existing ones.

This explanation aims to provide a basic understanding of object lifecycle in Python, highlighting the role of constructors and destructors in object creation and management. It clarifies that destructors are not always necessary and focuses on the concept of object creation, initialization, and destruction.

Object Lifecycle in Python: Creation, Initialization, Destruction

In the world of Python programming, every object has a lifespan, just like everything else. This lifespan is called the object lifecycle, and it consists of three main stages: creation, initialization, and destruction. Understanding these stages is crucial for writing clean and efficient Python code.

1. Creation

When you define a class in Python, you’re essentially creating a blueprint for objects. But objects themselves aren’t born until you instantiate the class. This is done using the class name followed by parentheses:

Python

class PartyAnimal:
    # Class definition

party_animal = PartyAnimal()  # This creates an object

In this example, party_animal now holds a reference to a newly created object of the PartyAnimal class. This object exists in memory and has its own set of attributes (variables) and methods (functions).

2. Initialization

Once an object is created, it’s usually uninitialized, meaning its attributes haven’t been assigned any specific values yet. This is where the constructor comes in.

A constructor, also known as the __init__ method, is a special method that gets called automatically whenever you create an object of a class. Its purpose is to initialize the object’s attributes by assigning them their initial values.

Here’s an example of a constructor:

Python

class PartyAnimal:
    def __init__(self, name):  # Constructor with a parameter
        self.x = 0  # Initialize self.x to 0
        self.name = name  # Initialize self.name with the provided argument

party_animal = PartyAnimal("Sally")  # Creates an object and calls __init__()

In this example, the constructor takes a parameter name and assigns it to the self.name attribute. It also initializes self.x to 0.

Note: The self parameter is a special reference that always points to the current object itself. It’s used to distinguish the object’s attributes from local variables within the method.

3. Destruction

When you’re done using an object, Python eventually removes it from memory through a process called garbage collection. This happens automatically when there are no more references to the object in your program.

While Python handles garbage collection efficiently, there can be situations where you might want to perform some specific cleanup tasks before an object is destroyed. This is where destructors come into play.

A destructor, also known as the __del__ method, is a special method that gets called automatically when an object is about to be destroyed. However, destructors are used less frequently in Python compared to constructors. They are typically only needed for objects that manage scarce resources like database connections or files.

Here’s an example of a destructor (although not typically recommended for most cases):

Python

class PartyAnimal:
    def __init__(self, name):
        # ...

    def __del__(self):
        print(f"Object {self.name} is being destroyed!")

party_animal = PartyAnimal("Jim")

In this example, the destructor simply prints a message when the object is destroyed.

Remember: Destructors shouldn’t be relied upon for essential cleanup tasks, as Python’s garbage collection is generally reliable. They are mainly used for specific scenarios where resource management is crucial.

Summary

By understanding the object lifecycle, you can write cleaner and more efficient Python code. Here’s a quick recap:

  • Creation: Use the class name followed by parentheses to create a new object.
  • Initialization: The constructor (__init__ method) is called to initialize the object’s attributes.
  • Destruction: Python’s garbage collection automatically removes unused objects from memory. Destructors (__del__ method) can be used for specific cleanup tasks in rare cases.

As you continue your Python journey, keeping the object lifecycle in mind will help you write more robust and efficient programs.

Now we’re going to talk
about object lifecycle. Like I said, we’ve been
talking about this all along, but now we’re going to be a
little more formal about it. Objects are created,
used, and discarded. You don’t have to think
about this too much, because it’s just
done automatically. This is a concept in
computer science that we call garbage collection
and that is when you’re done with an
object and you want to clean things up and you want
to get the memory back. We have special
blocks of code that we as the object
creator can say, you know what, I
want to be involved in the moment of creation and I want to be involved at the moment you’re
throwing this away. We use constructors a lot, that’s the under in it. You see that all the time. Destructors, we tend not to worry too much
about what happens when we’re going away because
usually all we’re doing is the memory is being
given back to the system. It’s not like usually
we have to do something unless your
object is really complex and has some
scarce resource perhaps that you’ve got in it
like a database connection. Again, that’s super
advanced stuff. I just want to talk
about constructors and destructors now, not that we’re going to use them at all in this class, literally. But when you start talking to databases and you’re creating connections and those things, that’s where a
destructor might be. There might be some
scarce resource that is connected to something
on another computer or something that you do
want to give back or something the operating system has that you do
want to get back. The primary purpose of
the constructor is to set up some instance variables to have the proper
initial values. I was calling it, it’s constructed and then
it’s initialized. The code that gets called
is the constructor code. This is the object oriented
term as constructor, but I think of it as
the initializer because the construction happens
before the init is called. The world calls a constructor
and no one’s going to be mad at you for calling
init, the constructor. There you go. In this one we’ve got a class party animal. The party method is the same. I just added a print statement to the constructor so we can see when that happens and a print statement which is already there in the party method. Then I have now added a double _del. Now the interesting thing
here is that’s also the same. There’s a del paren function
looking like thing, which actually is a shortcut
to calling this del method. Again, it’s a syntax
transformation because you actually can call del on an object in Python and it calls
this del method. All we did in here just
I’m trying to track how it’s created and destroyed. This destruction might be
counterintuitive to you, so that’s why I’m
going to do this. We’ve got instrumented
construction message, a method message, and
a destructor message. We create an = PartyAnimal which constructs the object and calls the init
method to initialize it. Then we call an party twice. Then this is the part
that’s a little weird. We say an = 42. Now, right before that,
an = 42 statement, an held an object. That’s what it was. Technically, it’s
pointing to an object but an was an object in our world. When we say an = 42, the object is gone. What happens is this
Python is like, well an was a party
animal object and now I’m going to
put a 42 in there. But right before
I put that 42 in, I better get rid of that object. You have caused the
destructor to be called by overwriting an that used
to have an object in it. I think that’s cool. Now you don’t have
to know about this because there’s memory inside
of the party animal object. But as soon as an doesn’t
have a reference to it, as soon as an is not
looking at it anymore, we want that memory back. Again, this is 12 bytes of
memory. It doesn’t matter. But if there’s millions
of these things, millions of strings that
you’re creating and deleting and using the same
variable over and over again, Python is carefully reclaiming the memory every time you
overwrite with a variable. If you look at the output, you see the construction. It starts which is that
first line an = PartyAnimal. Then you see party
method get called twice. So far, one, so far two. Then when we’re
assigning it to 42, out of the mist comes
this, I am destructed. The instance variable
self.x is still two, but a moment later
that object is gone. It’s been garbage collected. It’s been reclaimed
by the object system. It’s been reclaimed
by Python and can be used to create new objects. Then at the end
we just print out an contains an which is 42. We implicitly are
calling the destructor. Again, we didn’t have
any work we wanted to do in this destructor in
our party animal class. All I want to do is print
it so you could see that there is a life
cycle of creation, initialization, execution, and then destruction,
deallocation, garbage collection. In object programming, a
constructor in a class is a special block of statements called when an
object is created. Again, I hope by now
that’s intuitive. Many instances, we create
lots and lots of objects. The class is the template
for making these objects. We can distore each distinct
object in its own variable, and we call this having
multiple instances. Each instance, each object has its own copy of the
instance variables. Let’s take a look at this. In this code, we go back
to what we had before. We have added in the
init, another variable, self.name and we’re seeing that constructors
can have parameters. The constructor can have
a parameter that then we copy into the instance
variable, self.name. It’s really the
instance variable name. Self happens to be our alias
to the instance itself, and the dot means within. I like to read that
is name within self, is how I think of that. Then we print that we’ve
constructed it and we have our party animal
and that’s the same except we do print out the name. Then what we’re
going to do is we’re going to make a party
animal with a name of Sally and store that
in the variable S. That constructs
a party animal, puts in Sally, x =
0, name = Sally. Then we call the party
method on the Sally object. Then we call J, party
animal with Jim. We’re going to
make a new one and we’re going to store
that one in J. Then the constructor
is called again. This time z is Jim
and self.name is Jim. We call j.party which
calls the party method in the J object and s.party which calls the
method in the S object. Let’s track this through. At the moment we’re calling
party animal, Sally. We’re like make a thing then
call init and that will make the instance variable x be zero and the instance
variable name be Sally. Then we call s.party
and that increments the x attribute in the
S object to be one. Then we say, now let’s take that template
and build another object. But this time we’re going
to put Jim in is the name, and x is automatically zero. The same initializer was called as part of the
construction of this, and so it’s x = 0, name = Jim. Now you’re beginning to
see how the purpose of the code we write in init. That purpose is to get the things set up and
we’ve got two variables, we’ve got to put them in there. Then we can use them. Then we call j.party which adds one to the J instance
of our party animal, gets added to one and we still
have both of these things. J still exists and S still exists and we call the S party, and then x becomes
two in that instance. Again, I’m only showing you two, but there could be millions. You could have millions of strings and each of
those strings is a different instance and
has different attributes, but the same methods generally. Up next we’re going to
go the last little like, oh, you can do this too. It’s called inheritance. Inheritance is basically
our way of reusing code, defining one object, and
then creating an object that extends that object
and adds new capabilities.

Video: 14.4 – Object Inheritance

Summary of Inheritance in Python

This video introduces inheritance in Python, a powerful concept for code reuse and organization.

Key Points:

  • Inheritance: Allows creating a new class (subclass or derived class) that inherits properties and methods from an existing class (parent class or base class).
  • Benefits:
    • Reusability: Avoids rewriting code by inheriting functionalities from existing classes.
    • Maintainability: Changes in the parent class automatically apply to subclasses unless overridden.
  • Terminology:
    • Subclass/derived class: Inherits from another class.
    • Parent class/base class: The class being inherited from.
    • Super class: Refers to the parent class in the context of a subclass.
  • Example:
    • PartyAnimal class has attributes (x, name) and a method (party).
    • FootballFan class inherits from PartyAnimal, adds a points attribute, and defines a touchdown method that uses the inherited party method.
  • Key Takeaways:
    • Inheritance promotes code reuse and organization.
    • Subclasses inherit properties and methods from parent classes.
    • Understanding inheritance terminology is crucial.

Additional Notes:

  • The video emphasizes the importance of understanding inheritance concepts, even if you’re not an expert yet.
  • It highlights the practical benefits of inheritance in real-world applications like Django framework.

Inheritance in Python: Reusing Code with Elegance

Inheritance is a fundamental concept in object-oriented programming (OOP) that allows you to create new classes by leveraging the capabilities of existing ones. This tutorial will guide you through understanding and implementing inheritance in Python.

What is Inheritance?

Imagine you have a blueprint for a building (class) that defines its foundation, walls, and roof (attributes). Inheritance lets you create a blueprint for a specific type of building, like a house (subclass), that inherits the general structure from the building class but adds specific features like doors and windows (unique attributes and methods).

Why Use Inheritance?

  • Code Reusability: By inheriting from existing classes, you avoid rewriting the same code, saving time and effort. Imagine inheriting the functionality of a “shape” class to create specific shapes like circles and squares, each adding their own unique properties.
  • Maintainability: Changes made to the parent class automatically propagate to its subclasses unless explicitly overridden, making code maintenance easier.
  • Organization: Inheritance promotes code organization by grouping related classes into hierarchies, improving code readability and understanding.

Implementing Inheritance in Python

  1. Define the parent class:
    • This class holds the common attributes and methods that will be inherited by subclasses.

Python

class Animal:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def eat(self):
        print(f"{self.name} is eating.")
  1. Create the subclass:
    • Use the class keyword followed by the subclass name and the parent class name in parentheses separated by a colon (:). This indicates inheritance.

Python

class Dog(Animal):
    def __init__(self, name, age, breed):
        super().__init__(name, age)  # Call the parent class constructor
        self.breed = breed

    def bark(self):
        print(f"{self.name} says Woof!")

Explanation:

  • Dog inherits from Animal.
  • Dog‘s constructor (__init__) calls the parent class constructor (super().__init__(name, age)) to ensure proper initialization of inherited attributes.
  • Dog adds a specific attribute (breed) and a unique method (bark).

Benefits of the Example:

  • We reuse the name and age attributes and the eat method from Animal in the Dog class.
  • We avoid code duplication and maintain consistency in how animal objects are created and behave.

Conclusion

Inheritance is a powerful tool for code reuse, organization, and maintainability. By understanding the core concepts and practicing with examples, you can effectively leverage inheritance to build well-structured and efficient Python applications.

Additional Resources:

  • Explore online tutorials and documentation for further practice and in-depth explanations.
  • Experiment with creating your own inheritance hierarchies for different scenarios to solidify your understanding.

Now we’re going to talk about inheritance. I’m going to guess that among all
the things I’ve talked about, inheritance is going to be the part
where you go like I don’t get it. That’s fair, just don’t get it. It turns out that when it’s all said and
done, this is one of the most powerful capabilities and it has to do with store
and reuse, and don’t repeat yourself. We programmers hate saying the same
thing over and over again. Like in a Django model, which is
a future class every whole bunch of different objects need a date and
a time of create date and update date. Do I want to type create date and
update in 40 places or just extend a base class
called the date stuff? And so it’s a balance and
it’s a bit art form, but it is a form of store and reuse and
avoiding just pasting over and over. So every time you’re coding and you’re
pasting over and over, you’re like man, what if I want to change
all this stuff now? I got 40 places,
I just pasted this code in. And what if I mistyped the word create,
right, in created at like a date or something? So we like to not repeat ourselves. So back to inheritance, we can make a new
class by reusing an existing class and inheriting all the capabilities of
that class and then extending it. So there’s inherit and extend, and we’re
going to say, you know what, I like that, but I want to add a couple of things,
I want to replace a couple of things, etc. And so we call them the parent class or
base class, and then the child class or the derived class. So subclasses is another form for
the word for this. They’re kind of more specialized,
improved versions of classes which inherit attributes and behaviors from their parent
classes and can introduce their own. So let’s get right to it. So party animal, class party animal. We’ve done that before, right? That’s our stuff where I took
the destructor out, because remember, we don’t care much about the destructor. So we got an init method and
a party method and we got an x and a name. Been doing this for a while now. The interesting part is the bottom
part where I say class football fan. And the way I read this is class
football fan extends party animal. So now we put a parentheses
in the class statement, but that’s not an instance,
that’s another class. So what we’re saying is, and literally,
if I didn’t have anything below that a football fan would be another class
that’s identical to party animal. Because we’ve extended a class, which
means we inherited all of its capabilities and we haven’t changed anything and
we haven’t replaced anything and we hadn’t added anything. But now, after class, football fan,
party animal, we’re indented. And then we start doing some defs, and we def the double underscore
init double underscore. And we’re in effect, adding an init for
the football fan class. But it turns out the first thing we’ve
got to do is call the init in the party animal class. So that little gesture, super open
paren dot underscore, underscore, init, underscore, underscore,
open paren name, which is, of course,
that parameter that we’re passed in. That’s saying, before I do the stuff
I’m going to do in football fan, let’s make sure all the stuff
that is necessary for a functioning party animal,
let’s get that done. So we’re constructing a football fan and
initializing a football fan. But the first thing we do is
initialize the party animal, super, that is the superclass. We’re in a subclass, superclass is
the party animal is the superclass. Football fan is the subclass. And that super print, that’s just
hard coded, that’s a thing you say. And I don’t love this syntax. Other object owned approaches in different
languages use different syntax for this. This just is what it is, it’s a gesture. And then what we’re doing now is when that
super is done, there is going to be an x, and there’s going to be
a name in football fan. And then we’re going to
add another attribute. This is the extending part,
self points equals zero. So at the end of the creation of
a football fan, it will have a name, an x and a points, and
it will have a party method. But then we’re going to add
a touchdown method, and the touchdown method adds seven to
the points and calls the party method. So party is not in football fan,
party is in party animal. But because football fan has inherited
everything that is party animal, bada boom, bada bing, we have got
a party method, and we print it out. And so now if we look at the code
s equals party animal Sally. We can make one of those things and
we can call s party, and that j equals football fan of Jim. That’s going to construct a football fan,
which is then going to call the init method for football fan, which is that
init method is then going to call the init method for party animal,
come back, and then add points. So even though it’s not
explicit in football fan, we inherited the party
method from party animal. But then we can say j.touchdown,
because Jim is a football fan, not just a party animal, okay. So what I’m really gaining here
is I’m not repeating myself. I wanted that party method. Now, in real code, the party method will
be something useful, like uppercase or lowercase or reverse or
something like that. And you’re like, I don’t want to rewrite
the reverse function in this new thing. We might have a thing called
uppercase string or something. So if we look through the code, we see that at the moment we
construct the party animal. It’s set x to zero and the name to Sally
because it calls the init method of party animal, because it’s not a football fan,
it’s just a party animal. So party animal is, in effect,
unaware that football fan exists, and we can just use it like a class. And then we call the party method,
and then that adds one to x. Then we go to the next line,
and we make a football fan. So as the initializer for
football fan runs, which then calls the initializer
party animal, then comes back and finishes the initialization of football
fan, we’re going to end up with an instance variable of x of zero,
a name of Jim, and a points of zero. So that means it’s fully constructed and
fully initialized. And then we call the party method,
and it adds one to x, and then we call the touchdown method,
and it adds seven to the points. It’s kind of intuitive, it’s not too bad. So way we, so
now we have two instances, but we have instances of a different class. But one of the classes, football fan, in
a sense, includes inside of it everything that’s in the party animal class
because party animal is the base, class football fan is the subclass. Party animal is the parent class
football fan is the child class. Party animal is a class,
football fan is a derived class. All that terminology that you might
hear in a book or whatever, it’s for all intents and purposes, the same thing. So now we’re going to kind of summarize
the definitions of all this stuff. A class is a template. It’s not a thing,
it’s the definition of a shape of a thing. It is the cookie cutter. It has all the details of what that
thing’s going to be when it’s done including what attributes it’s going to
have, what methods it’s going to have. But then when we make one,
we make a cookie that’s an object, but when we make a cookie,
it’s going to call the constructor, sets the cookie up with
default values generally. And then inheritance is the ability to
say, you know what, I like this class and I want to change it just a little bit and
do my own thing. Sometimes people will build
classes in various situations, and Django is a good example of this, where
they’ll build classes that your job is to extend it and you’ll put
a little tiny bit of stuff in it. And then all of a sudden you
get like tens of hundreds of, not thousands of lines of code that
you get for basically for free. So these sets of definitions is what
I wanted you to learn in this class, and I don’t expect you to be like
a ninja warrior of object oriented programming at this point. I just want you to get used to me saying
over and over and over again, object, constructor, destructor,
method, attribute, I’m going to just say those words. For all the classes I teach from now on,
I’m just going to say those words and I just want you to understand them. So I hope you have enjoyed and
gained something from this quick high level pass or
object oriented programming in Python.

Assessments


Quiz: Object Oriented Programming

Which came first, the instance or the class?

In Object Oriented Programming, what is another name for the “attributes” of an object?

At the moment of creation of a new object, Python looks at the _________ definition to define the structure and capabilities of the newly created object.

Which of the following is NOT a good synonym for “class” in Python?

What does this Python statement do if PartyAnimal is a class?
zap = PartyAnimal()

What is the syntax to look up the fullname attribute in an object stored in the variable colleen?

Which of these statements is used to indicate that class A will inherit all the features of class B?

What keyword is used to indicate the start of a method in a Python class?

What is “self” typically used for in a Python method within a class?

What does the Python dir() function show when we pass an object into it as a parameter?

Which of the following is rarely used in Object Oriented Programming?

Bonus


Video: Bonus: Interview – Software Engineering – Bertrand Meyer

Summary of Bertrand Meyer’s Speech on Eiffel Programming Language:

Early exposure to Simula 67:

  • Introduced to Simula, an early object-oriented programming language.
  • Recognized its potential and began working with it extensively.

Founding of Eiffel and Initial Struggles:

  • Collaborated with colleagues to create a new language based on Simula concepts and formal specification experiences.
  • Faced initial skepticism about the need for a new language in the market dominated by AI-oriented and C++ approaches.

Eiffel’s Key Differentiators:

  • Focus on design and maintainability: Prioritizes clean designs that can be easily changed and extended over time.
  • Contract-based programming: Enforces preconditions and postconditions for routines, improving code reliability.
  • Holistic lifecycle approach: Offers tools and methodologies for all stages of software development, from analysis to testing.
  • Uniform access principle: Treats data access and function calls similarly, simplifying code structure.

Target Users and Applications:

  • Ideal for complex, mission-critical applications requiring high reliability and frequent changes.
  • Used in various domains like finance, aerospace, healthcare, and education.

Benefits for Developers:

  • Reduces context switching between different tools throughout the development process.
  • Provides a consistent framework with core concepts like classes, inheritance, and contracts applied across all phases.

Overall, Eiffel positions itself as an alternative to mainstream approaches, emphasizing design quality, maintainability, and a unified development experience.

[MUSIC] I had the great privilege and good
fortune of being exposed to Simula 67 which was after 67, I’m not that old. But still Simula kind of was the
was still the dominant view of object oriented programming at that time, which
very, very few people had encountered. So Simula was the first
object oriented language, and well it was quite confidential. So kind of best kept secret for
many years, but I got introduced to it, and I immediately knew that it
was the right way to program, it was pretty obvious, at least to me. And so for a number of years I
worked with Simula both on paper, to help my research work, and
to build systems. >> Bertrand was teaching at UCSB and well, of course, he had already in
France started some projects. So his ideas, he came already with some ideas and
projects to UCSB. And he continued, and
he shared that with his students, and suddenly one night he comes back home and
says, well, I have a student from Japan who is excited
about my ideas and he wants to talk to his company about it. I said okay, well. It was a new idea. Why not? But I did not really believe in it. But several months later,
Bertrand came home and said well the company is
interested in my ideas, and they are ready to start
to help us start a company. So there it was, and that was
the beginning of the second adventure. The first adventure was the move
to the U.S. with five children. >> I found myself in ’85 in Santa Barbara
with a newly created company, building a system which
was called ArchiText and which was a very smart editor, on initially with funding
from a Japanese company. And well I was looking for
a tool to build it, to build that system. And while Simula was kind of
fading out at that time I looked at C++ which was there. I opened the book,
I closed it pretty quickly afterwards. There was Objective C, there was SmallTalk,
these were all interesting developments. But they didn’t really correspond to
the kind of strict software engineering standards that my colleagues and
I had learned to observe, so we developed our own
language which was based on, well the full story would,
of course, be longer. But I had written a book which I never
finished, but which had a very precise notation for expressing algorithms
at the time, so I used that. I used my work on formal specification. I co-wrote the first paper on
the Z specification language. So my work on Z and also a successor
to Z, which was called M, was also very influential. So, over a half a day,
I kind of put all these together and we implemented a pre-processor to, well, we thought of it right from
the start as a compiler to generate C. But it was really just for
internal purposes. And then what happened is,
that we went to OOPSLA. The first OOPSLA in ’86, where the company
had booths, or rather a makeshift booth. We didn’t have that much money. But then we were actually
showing the other tool but people wanted to see Eiffel. >> Well at OOPSLA,
Bertrand had some tutorials and that was the first place where Eiffel was really exhibited, and
from then on it was clear that the focus of the company
was more on that technology, on the tools to help programmers make the most of power of
object oriented technology. >> We realized that contrary
to what I had thought, no one else had anything similar
because everyone else was going into these kind of AI-oriented developments,
experimental programming, no typing, no idea of course of generativity because
without typing there is no need for that. Or the kind of C++ direction, which is of
course also respectable, but which to us was a diversion, or a transition to help
people move to the object oriented world, but didn’t seem like an end in itself. And I’m not saying this to deprecate
C++ because obviously it’s been a very successful technology, but to still think that it’s best viewed
as as a transition technology. So we realized that there was nothing
like it and when we came back from OOPSLA we started kind of refocusing
the company. And there’s also something very
important which happened at that time. Which is that people who started
playing with the language, even with the primitive
implementation we had at the time, started telling us. you know, there’s
something absolutely new which I’ve never seen before,
it’s how easily you can change your mind. And I would say today this is still
one of the major assets of Eiffel is the flexibility, to use the technical
term, the extendability. So the people don’t necessarily believe us
when we say this because it’s like hand waving and to some extent everyone says,
oh people talk about flexibility. But this is perhaps one of the major
differences between Eiffel and other technologies is how easily you can
have a first design, a clean design. I’m not talking about agile style
hack it and see if it works. Really, a good design,
which however is not perfect, you realize it is not perfect,
you change it and you don’t spend your entire life paying
for the sins of your youth, so to speak. And it’s not one single aspect, it’s not one single feature of Eiffel,
it’s a collection of things. It’s contracts, it’s the modularity mechanism,
the information hiding mechanisms. It’s the principle of uniform access. Something that Simula actually had got
right, but later languages didn’t. The idea that you don’t
distinguish from the outside between accessing a piece of data and
calling a function. Which even UML which should be high level,
didn’t quite get right, so that’s it’s a whole set of seemingly
small properties, that together make a, give a framework in which you
can change your designs and integrate new ideas very easily and
very quickly without suffering too much. So this is what people started
telling us right from the start and which really encouraged us to build
the company, the technology around Eiffel. To characterize the typical Eiffel user, well this is someone who typically
has a difficult application. So an application often for which he or
she has tried something else before. Maybe a couple other
technologies that failed. You know hit limits of complexity or
limits of reliability and then doesn’t have a choice and
he wants it really to succeed. And so it can be in the
financial industry where some of our biggest customer applications
are, it can be in the aerospace industry, which is also another strong area for us,
it can be in healthcare, sometimes also of course in education which is kind of
a different kind of application of course. But it’s people who just cannot afford
the stuff to fail. So that’s one characteristic,
it’s that the reliability and quality requirements are
typically very high. often with continuous operation for
systems managing to wait for, this kind of thing. A second characteristic is that these
applications often need to undergo much change over their lifecycle, which may be
years or decades. And here the extendability
mechanisms of Eiffel really shine. One of the key distinctive features of
Eiffel is that it’s a lifecycle approach. So it’s not just for programming. Not only is it not just a language but
also it is not even as a language it’s not just for programming. It’s for analysis, it’s for design, it’s
for implementation, it’s for maintenance, it’s for testing, and so on. So it’s really, it’s kind of a holistic, to use a pretentious term,
view of software development. So this is kind of really still going
against the grain of the software and engineering culture today. Most people think they need some kind
of high-level requirements tool, some case tool to do analysis and design, and then Eclipse or something or
Visual Studio to do implementation, and then JUnit or
something like that to do testing, and what we do is that we integrate everything. Which means that for
the developer you don’t have this need to switch between Dr.Jekyll and Mr.
Hyde all the time. To switch personalities. To switch gears, context, and so on. You stay in the same conceptual framework. And the basic ideas of Eiffel which are
classes, inheritance, single and multiple. Multiple inheritances are important. And of
course, as you pointed out, contracts, the use of formal precise specification elements
in association with every piece of software, these ideas and a few more apply
throughout the lifecycle, throughout the process,
from the highest. most abstract levels of thinking about the system,
all the way down to the nuts and bolts, the nitty gritty of software construction,
debugging, testing, and so on. Although debugging, as you say, we try
to have less debugging with Eiffel but well, you wouldn’t believe me if I
told you that there are no debugging at all when in fact there is a quite
powerful debugger in the environment. [MUSIC]

Video: Bonus: Office Hours – London

Summary of Online Course Office Hours in London

This video provides a glimpse into an online course office hours session held in London. Here are the key points:

  • Host: Chuck (not seen, but leading the session)
  • Location: Hammersmith Tube Stop, London (presumably near attendees)
  • Attendees:
    • Jerry
    • Nico (first online course)
    • Magic Magic (appreciative of the course)
    • Tara (enjoyed the course)
    • Nick (enjoyed the course very much)
    • Jonathan (cheating slightly as he remembers the material, but finds it helpful)
  • Highlights:
    • Attendees introduce themselves and briefly share their experiences.
    • Chuck interacts with attendees, acknowledging their certificates and previous course participation.
    • The session concludes with a positive sentiment.

Overall, the video offers a brief snapshot of an online course fostering interaction and community among geographically dispersed students.

[SOUND] Hello this is Chuck here, and we are in London at
the Hammersmith Tube Stop. We just had about an hour
of Office Hours and I’d like to introduce you to
some of your fellow students. Say your name and
say hi to the rest of the students. >> Hi I’m Jerry. Hello.
[LAUGH] >> Hi, my name’s Nico. And this is my first
course I ever did online. It’s great.

Hi, my name’s Magic Magic, and I appreciate the course,
and everything like that. >> Oh, hey. Get your certificate out. I’ll come back. Get your certificate out. I’ll come back to you. >> Hi, I’m Tara, and
I really enjoyed this course. >> Hi, I’m Nick, and I,
too enjoyed it, very very much indeed. >> Hi, I’m Jonathan, and I’m cheating
slightly this course, because I remember a lot of this stuff, but
with my history, it’s been really good. >> Well, cool,
let’s take a look at your certificate. So you were in the previous course, right? So you got a certificate, and
we got the certificate signed so, okay. So there we have it. Another successful
Office Hours here in London. So see you all on the net.