9. Python Classes and Inheritance
Вставка
- Опубліковано 14 лют 2017
- MIT 6.0001 Introduction to Computer Science and Programming in Python, Fall 2016
View the complete course: ocw.mit.edu/6-0001F16
Instructor: Dr. Ana Bell
In this lecture, Dr. Bell continues the discussion of Object Oriented Programming in Python, with an emphasis on data control, inheritance, and subclasses.
License: Creative Commons BY-NC-SA
More information at ocw.mit.edu/terms
More courses at ocw.mit.edu
0:02:05 Implementing vs using class 0:04:00
0:06:56 Why use OOP and classes of objects
0:08:58 How to define a class (recap) 0:10:59
0:12:00 0:13:12 0:14:38
0:16:36 Python not great at information hiding
0:18:16 0:20:00 0:22:00
0:23:02 Hierarchies
0:24:46 Inheritance : parent class 0:26:30
0:28:14 Class person 0:30:00
0:31:04 Class person(Coding)
0:32:00 Class student 0:34:39
0:36:35 Class variable and the Rabbit subclass 0:38:51 0:40:00
0:42:18 Rabbit getter methods 0:43:48 0:46:31
好学生
I have watched the nine lectures so far, and realized this is exactly the information missing in all those coding schools online, which try to dumb everything down, let you fill in the blanks in a code (as an exercise), but fail to teach how Python actually works underneath the surface. The logic of Python or coding in general should be taught more, because that makes you understand what the heck you are doing.
Yeah, exactly. These other courses are always like "this is how you have to do it and it is what it is" but actually if you want to get better and not just copy code from a tutorial, you need to understand why it is that way and how it works beneath the surface.
*My takeaways:*
1. Getter and setter 11:05
2. Why it is better to use getter and setter: information hiding 13:25
3. Python is not great at information hiding 16:25
4. Default argument 17:58
5. Hierarchies 23:01
6. Override behaviour 24:05
7. An example 28:14
8. Class variables 35:45
I must say....this class is the most informative class I have taken on programming. Most classes are just ramblings and ego validation/marketing gimmicks by "instructors". I am actually learning stuff that I can implement, ain't that something.
I love this woman. I'm studyng programming and Python more than a year now and I started with this course. She was, untill now, the best teacher I've ever seen. There is David Malan, from Harvard, also very good, but she always seemed the most clear for me. Perfect.
David is much better imo
Thank you very much !!! I use the Udacity for building CS project and portfolios, but since I have no CS degree, MIT online is the best resource for me to reinforce the core concepts for the foundation of CS on each topic, which bonds all of my fractured pieces of CS knowledge into a holistic picture. Very useful!
Hey James, I'm doing the same curriculum as the MIT 6.3 program in EE & Computer Science using MIT OpenCourseware. I have a slack team if you want to join.
Juan Vicente i would love to, i am a beginner
I want in
@@user-nq5wb1cz5e i want to join and i will be thankful for acceptance
@@user-nq5wb1cz5e hey, some of the courses are not online, how do you work around that
Very clear, thanks to the lecturer (Dr. Ana Bell) and the anon cameraman!
Best intuitive lecture about classes and objects ever came across in the internet
When 2 rabit objects at 43:23 are added together they bond and produce a new child rabit.. Wow thats the power of OOP
Another extraordinary lecture, very informative and well explained
Found this clear and concise. Fantastic lecturer, certainly knows her stuff. Thanks :)
Although i am CS major, i still learned a lot from this course. thank you !
MIT open courses never disappoint = ]
Absolutely well done and definitely keep it up!!! 👍👍👍👍👍
The class is really good but it would be easier to follow if it was constantly focused on the slide.
Thank you for sharing this!!
Əla. Çox dərinlərə enməyib ama faydalı məlumatlar var. Thank you very much.
Thank you, MIT. For those complaining about not being able to see the slides. Click the link in the description and download the slides. Quit complaining about receiving a free, world-class education. Take two seconds, read the freaking description and go view the complete course!
Thank you so much for these great lectures.
Awesome lecture much love from Sri Lanka
30:14 "I want to make a note that I actually didn't write a method to remove friends, so once you get a friend, they're friends for life... but that's ok." Anna that's a life lesson there...
Note that in this lesson we decide that any two rabbits with the same parents are "equal". This could be weird, and probably is, however, that is outside the scope of Python or programming. Many people and some rabbits would object to be thought to be equal to their brother or sister.
Really good, tyvm!
Hi,
Why with the class cat(Animal) example do you leave out the __init__ statement, but with the person (animal) example do you include the __init__ statement of animal.__init__ etc....?
If the cat example inherits name, age etc.. of animal class then why do you have to write Animal.__init__(self, age)? Won't the person class inherit this without the statement and if not what makes it different to the cat class?
Thank you
Not sure if you still need this,
class Cat has the exact same __init__ function as Animal.
Since the class Person has a different __init__ function everything needs to be redefined, Python will not look further up the 'ancestry' for another __init__ function if class Person has one.
Animal.__init__ just saves you some lines of code. If Animal.__init__ had a bunch of attributes and you wanted to inherit that into class Person, but Person's __init__ had to be somewhat different you can just type Animal.__init__ instead of retyping the whole Animal __init__ function
If there's a part you still don't understand a part feel free to ask more questions
You only need to write an __init__() for a subclass if something different is done at initialization. If you do write __init__ for the subclass, you're overwriting the superclass __init__, which is why you have to call the superclass __init__.
Why is the camera most of the time focused on her, while she is refering to something on the slide?
use the slides from the link along with the video.
thank you so so so much !!!!!
Thank you,,,, helped me ....
So clear!
It would help to show her screen with the code more of the time
It's really helpful!
this video is awesome
If it's not a good approach to use direct dot referencing than getter and setter, why Python allow it? Is there any philosophical reason for this?
It goes against the principle data abstraction of OOP.
It would be much better to have focus on lectures slides in the video than on the lecturer. WE can't open another window side by side showing the associated pdf slides as some suggest. Some of us watch these lectures on average sized iPads and laptops with small screens. MIT really need to shrink time instances showing lecturers and put more focus on the actual " content" being taught. These video are mostly showing the lecturer even when her gestures do not aid any extra learning. I genuinely appreciate putting these lectures and am really thankful as well as appreciate the fact that Ana is very knowledgeable and She explains things very well. But lack of slide time really makes it frustrating to absorb the information. Instead of expecting/telling us to open separate lecture slides it would be much better if videos themselves spend more time on the said slides, preferably most of it. I assume cameraman and video editing team never really learned any scientific material themselves and do no know the importance of slides as a learning aid.
Thank you!
Can I call a class' method w/o making an instance of it? For example, Anna is using a method of 'random' class which she imported w/o instancing.
It depends on the method you are calling. If the method does not have as argument the class or object (self), it is possible to use it without creating an instance of the class.
Such methods are called "static methods".
You can call the method the following way (assuming it does not need any arguments):
import my_module
my_module.MyClass.method_I_want_to_call()
With the random method that Ana used, it's actually a bit different.
When writing "import random" what is imported is a module, not a class. The module contains the class named "Random".
If you look into the random module, you'll see at the bottom that the variable "random" gets assigned the method "Random().random". This allows us to then call the random method just by typing "random.random()" instead of "random.Random().random()".
Here we actually are creating an instance of the class Random, by typing "Random()" instead of just "Random". This is required because the random method requires an instance of the class (it's not a static method) and thus cannot be used just by typing "random.Random.random()".
You can privatize attributes in python classes by prefixing them with '__'. So self.friends becomes self.__friends, self.age is self.__age, and etc.
I can still call this outside the class though, so its not private in the same sense as in Java for example?
@@AS_20231 You can call it but you cannot modify it.
what is abs(diff)?
hey One thing it was previously set 'years' instead of 'age' but then she put "diff = self.age - other.age" instead of "diff = self.years - other.years"
In C++,we have access modifiers to protect data member from being modify outside of the class.But in python,there is no such mechanism.
it's me who shared this video with you shanu akka,thisa,didula,
Excuse me but I don't quite understand why the __eq__ method will be called over and over again when comparing objects directly.
Thanks in advance~~^^
Me to
say you got r3 = r1 + r2. for r3, self.parent1 is r1, self.parent2 is r2, now, you are comparing r1 == r2, but hold on, '==' is '__equal__' in this class, so it creates a new scope, for r1 self.parent1 = None, self.parent2 = None, look again, for None, self.parent1 is ERROR.
why 1 == 2 won't get you the ERROR msg? They are integers, not from the rabbit class.
@@MrSimonsmoke The way operator overloading works in Python using the Python data model is that various functionalities needed to use the built-in operators with your types are provided by various functions with conventional (by agreement) names with __ at the beginning and end of the name. __init__() was the first one taught about in this course. So whenever Python sees == between two operands that are Rabbit type, it will be calling __eq__( , ) ... so I think that was the missing point you weren't seeing.
why to write Animal__init__(self, age ) at all? in 28:54
Finally I understood class
What's that end variable in Student class code when she was running exercise on it.
the print() function automatically has a '
', or new_line after it is called. However, you can manually change it such that you don't have a new_line or want to instead want to have a '\t',or tab, after each print by modifying 'end'.
@@maxyang5143 thanks Max. I have come a long way. I surprised myself. I didn't know this 9 months back and now I am working as python developer. Phew..
thank you ,mit
Interesting lecture but I have never seen a real world example as to the benefits of Classes and OOP versus Functions, there is so much associated jargon. Can someone show me an example
Try to write a snake game using some graphic API.
Running a code analysis in Spyder told me classes automatically inherit from object in Python3, so in Python3 at 9:52 you can write
class Animal():
def __init__(self, age):
self.age = age
self.name = None
thanks mate
I like the rabbit search comment 😂 laughout 😂 right!
why do we have a self.name=None? what does it do?
It creates a variable on all class instances with Default value None.
How to delete "#" on different line at once?
first, mark the lines from where you want to delete '#'. then use ctrl + 1.
thank you
if you’re using python idle, highlight the lines that you want (shift + arrow key), them use ‘alt + 3’ to add # and ‘alt + 4’ to remove #.
almost done with this cousre
She recommends using getters and setters in python (13:47). But they are not needed and should not be used. If some transformation or checking of the data is needed, then properties should be used.
How come?
This class would be much better if given by any of the leading male programming youtubers.
"Not recommended to access data attributes directly?" This is Python, not C# or Java. Data attributes are part of the public API. (We're all consenting adults here.) If you need to validate data before setting or getting a data attribute, you can implement a @property without any change to the public API.
While I agree with you it should be pointed out that this is a comp sci course and not a Python course. This introduction has to be general enough that it gives you a feel for everything.
Yer, I thought so too. Literally trying to do it the java way, e.g the toSring @override. That said, she's great lecturer.
this is a lecture about basic programming concepts, not a lecture in Python specifically.
Definitely agree. Although she's doing a great job lecturing about general programming, it doesn't make much sense to use Python as an example without clearly calling out the distinctions, especially in the case of accessing data attributes. It's a lot like teaching someone the general rules of driving but forgetting to mention that not everyone in the world drives on the same side of the road.
very smart Canuck 👏👏👏
Lets find out what happens when you add two rabbits together - in this class, not the real world XD I love Dr Ana she is a legend
@ u teacher cb
akeh
The lecture is great but the editing is horrible. More than 80% of the on screen time is on the lecturer when it should be on the slides.
Could've at least have a minified window for the lecturer if you wanted to split screen it.
This is done on purpose, why would you want the camera on the slides if you can download the slides.
@@franciscogutierrezramirez5497 She point at the screen while explaining the concepts for the students to follow along... which we don't get to see. By your logic she should be pointing the lazer at herself.
ok
A lot of the class init she shows is specific to python 2.x. In 3.x you don’t need to explicitly inherit from object, for instance
What is the point of naming the class variable self.rid? She never used it, I don't understand that. If she directly used Rabbit.tag on the last line what was the point of creating that instance variable? Can someone please answer this? Thanks
Would be good if camera man/woman stays focus on the screen instead of the lecturer!
thankfully the lecture slides are provided at the course link in the description
Don't need to see the lecturer period! Keep the camera focused on the screen!
the videography kinda sucks...the ppt should have been given more screen time instead of showing the instructor.
It would be easier to follow what she is saying if the code is visible.
Code snippets are available at: ocw.mit.edu/6-0001F16. Best wishes on your studies!
too much focus on teacher than the slides she is referring to. why ? please show slides when its refereed and not person speaking.
I have the exact same qualm.
You can go to the course page and download the slides for yourself
Listening at 1.75 X
"Image of kittens source unknown"
:)
I thought people at MIT are really smart, but look at them filming the professor pointing at the code/slides instead of filming the code, which is what we, students, really care about.
22:03 Maybe a cat has a data attribute for the number of lives they have left
LoL that was funny... but no one laughed :(
Good lecture , thank you
but I don't agree with you that persons are animals
Surely she is a great teacher, but in this lecture I feel she is not at her best.
MIT should fire the guys who made these videos.
What is the point to keep screen focusing on the instructor face when she is presenting based on the slide content???
Is her face showing the ppt contents?
The only point to focus on the instructor is when she is interacting with audience or doing some demo with pops.
This is when Java lecturer does part time job for Python... getters and setters are not pythonic! No one should recommend them as remedy for data hiding, which as an idea, was rejected by Python designers. This class teaches you how to pretend you still use Java when programming in Python ;-)
I know nothing bout dis shit only clicked for the kittens in the thumbnail
Everyone does a horrible job teaching get and set ... It's read write capability... That's pretty much it .
She is so anxious that she swallows every 30 seconds and is about to go into a panic attack. Give her a bag to breathe, please. It is very difficult to follow a teacher who, in addition to the above, also corrects herself almost every sentence, because the first time she says slightly incorrect things.
Do people actually pay money for this "education"? It's not even funny.
If you need frame of reference, watch the teacher at Stanford's CS193p teaching ObjC / Swift for absolute beginners. It's right here on YT.
People pay for this?
Is that a problem?
@@SatyamSingh-nq2il I can learn this for free.
Did she give all lectures on the same day? She is wearing the same clothes across all lectures..
Probably the least useful video on Python I've ever watched, but thanks anyway
Don’t use getters and setters in Python, just Google it and you’ll lots of explanations why: it’s useless in Python and poor form-sure mark of a noob.
This video is an academic monstruosity. It communicates nothing. It is a bizarre antropo-zoology class. For instance, it simply states that getters and setters ARE used etc. But why should one use them ? "To prevent BUGS ???" Pursuant this logics, everybody, except this lady, is striving, when writing code, to obtain a number of bugs as great as possible.
This Video never tells WHY one should use OOP. It never points to profit of using OOP and it never warns on what the damage is when not using OOP.
Use OOP to create "layer of abstraction" ??? I have a processor-ache. Horror !
@Ken MacDonald Your brain is advanced (and immense). You have probably graduated from MIT, too. Being fed with their greasy, insalubrious didactic junk, no wonder that You have understood nothing. Now, just to tackle your stupidissime comparision: if supposing that i would love to change my oil, this "lesson" does not at all present any of the concrete steps involved in changing oil, instead it will take me on a hallucinating journey in which changing oil is an intricate, frightening, scholastic systemic complication that M.I.T. will kindly "explain" by resorting to fluffy cats, obese barking bunnies etc. And yes, i should ask why a car should be purchased, simply because in engineering (all the more in comput. eng.) one must ask him(her)self a huge arborescence of 'why's. In addition, the 'complain' segment of your example is greatly noxious: with individuals like you, university super-gods remain unaccounted for (regardless of their incompetence, lack of pedagogical talent, lack of imagination, mental chaos etc), something that it is very unlikely for the ordinary employee. But, hey, do not worry: instead of delivering, these fellas skin you alive of the off tuition dough.
lolol, good humor
Time: 34.34
I keep getting an error en the definition of class Student. So, here is what I found:
print("
---- student test ----")
s1 = Student('Alice', 20) #instead of: ---------------> s1 = Student('Alice', 20, "CS")
s1.major = 'CS' #add this line
s2 = Student('Beth', 18)
s2.major = None #add this line
print("s1: ", s1)
print("s2: ", s2)
print("El nombre del objeto s1, clase Student-is-a-Persona-is-a-Animal: ", s1.get_name()," y dice: ", end = " ")
s1.speak()
print("El nombre del objeto s2, clase Student-is-a-Persona-is-a-Animal: ", s2.get_name()," y dice: ", end = " ")
s2.speak()