Line 11 will run regularly and create an object of class Circle with a radius 5. Line 12 will give us an error because the __init__ method did not set a default value for the radius, and you are not allowed to create an object of the class Circle without giving it a value for the radius.
Now, on to line 6. Any method can be run by accessing the objectname.methodname(). Every single method must be defined with at least the parameter (self) - think of it as the class making sure that it can access it's instance variables. Here's some sample code to demonstrate OOP a little more complexly:
You can see I've made 2 different objects of Circle with 2 different radii. obj1.radius gives a different value than obj2.radius because they are different Circle's with different properties. This is what the shell would show following having run the program:
Methods initialized with double underscores on either side are special, because they are called without being explicitly called - i.e. they are called when you perform other manipulations on objects. An important thing to realize about objects are that they are packages of data. If you say you want to to "ride the Six Flags Theme Park", you'll likely be looked at in an odd manner because this makes no sense - rather, you want to go to the Six Flags Theme Park and ride the individual rides. In a similar way, you can't add two objects because they are not single integers, they're much more complex than that. For example, if you try to do obj1 == obj2 without defining a '__eq__' method in the class, the computer will try and compare the memory addresses of the objects to see if they are the same object. Remember: if I create two objects with the same attributes, they are still separate packages of data that exist at two different addresses.
Here are some important methods you should define in a good class implemented for Circle:
And demonstrated in the shell:
Now that you've seen and understand some uses of OOP, I'd like to a few words on the magic of this concept:
Object oriented programming allows one to set up organized and efficient code, and helps you avoid having an overload of variables and oddly represented data. Yes, classes are like recipes, thank you Grade 11 ICS teacher (refer to Week 6). A class sets up the structure and blueprint of something that has the potential to exist in memory - creating an object takes that structure, copies it, and allows you to create a tangible set of data that is organized and makes sense. OOP makes way for Abstract Data Types such as trees and linked lists, which are all based on the concepts presented in this post.







No comments:
Post a Comment