Classes and instances

Let's look at an example of creating a simple class and methods, plus some instances of the class:

Class and instances

The class is defined on line 22. We use the statement class, followed by the name of the class. Normally, when the class object is defined, there are no parentheses at the end; parentheses are only used for functions and methods. However, the old way of defining classes used parentheses, so you may see that in many programs you come across.

After the class is defined, two methods are defined as well: setName() and display(). The first argument in the parentheses for a method must be self. This is used to identify which particular instance is calling the method. The Python interpreter handles the calls internally, so all you have to do is make sure self is where it's supposed to be so you don't get an error.

Even though you must use self to identify each particular instance of a class, Python is smart enough to know which particular instance is being referenced, so having multiple instances at the same time is not a problem.

self is similar to this, which is used in several other languages, such as Java. Even if you have no arguments for a method, you must still include self so Python knows which class instance is being referred to, as demonstrated with the display() method.

If there are any arguments that are passed to a method, such as name in this case, they will follow the self argument. When you are assigning arguments or other objects to variables, such as self.name, the variable itself must be qualified with the "self" title. Again, this is used to identify a particular instance.

The two methods, setName() and display(), defined in the class simply accept a string argument and assign it to a "name" variable, and then print that name to the screen respectively.

Moving on, lines 23-25 create instances of the Knight class. Here, you'll notice that parentheses make an appearance. This is to signify that these are instance objects created from the Knight class. Each one of these instances has the exact same attributes, as they all inherit from the same parent class.

Lines 26-28 call the setName() method that is defined in the Knight class. However, each one is for a different instance: x, y, and z each has a different value for name. This can be seen on lines 29-31, which show the name that was set for each instance.

You can assign values to attributes in an instance during instance creation (lines 26-28) or by explicitly assigning to instance objects after creation (line 32). On line 32, we overwrite the name that was initially assigned to instance x by assigning a new name with the = sign. Generally speaking, you can do this with any instance at any time, assuming it's not a read-only parameter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.134.133