class

When defining your class methods, you must explicitly list self as the first parameter for each method, including __init__. The self means the object itself. Writing this parameter as self is a strong convention.

When you call a method, the object itself is passed on as the first argument to the corresponding function. This is done by Python automatically, you don't need to provide value(the object itself) to parameter self. Such as the example of Apple class, we call a method say(self) like this:

apple2.say()     # no value inside the parenthesis is needed

the first parameter of methods is the instance the method is called on.

A peculiar thing about methods (in Python) is that the object itself is passed on as the first argument to the corresponding function.

Generally, when we call a method with some arguments, the corresponding class function is called by placing the method's object before the first argument.

This is the reason

In your example, when an instance of school is made, that particular instance is referenced, it will have its own age and name variables, separate from any other school instance that may be created.

A "self" variable can only be directly used by a specific instance, rather than any thing else. If you want to use those variables, you have to clarify by using dot notation, e.g. apple2.color school_one.age,

==

Generally speaking, instance variables are for data unique to each instance

and class variables are for attributes and methods shared by all instances of the class:

class Dog:

    kind = 'canine'         # class variable shared by all instances

    def __init__(self, name):
        self.name = name    # instance variable unique to each instance

Often, the first argument of a method is called self. This is nothing more than a convention: the name self has absolutely no special meaning to Python. Note, however, that by not following the convention your code may be less readable to other Python programmers,

Any function object that is a class attribute defines a method for instances of that class.

Methods may call other methods by using method attributes of the self argument:

class Bag:
    def __init__(self):
        self.data = []

    def add(self, x):
        self.data.append(x)

    def addtwice(self, x):
        self.add(x)
        self.add(x)
====old

results matching ""

    No results matching ""