Post by account_disabled on Dec 14, 2023 11:15:23 GMT
These variables form attributes of the class. Behavior of the class As discussed, behavior of the class is defined by the methods inside the class. But before going into the discussion on behavior, we have to start discussing the “self” parameter, which we used C Level Executive List in the __init__(). Self: In a very simple term, whenever we attach anything to self it says that the variable or function belongs to that class. Also, with “self”, the attributes or methods of the class can access. Methods: Class methods are functions inside the class which will have their first argument as “self”.
A method inside the class is defined using “def” keyword. class Animals: type=”mammals” def __init__(self,name,legs): self.name=name self.legs=legs def bark(self): if self.name==”dog”: print(“woof woof!!!”) else: print(“not a dog”) In the above method “bark”, as we are using the name variable, which is an instance variable, we are accessing it using “self” and this function would print “woof woof!!!”, only if the name provided to the object, is dog.
We have discussed most of the components of a class, but you might be thinking how to see if the class is working. The answer to this is unless we create an object of the class, we will not be able to see what the class is doing. Now, Let’s define and create an object of the class. Objects in Python An object is an instance of the class. A class is just a blueprint, but the object is an instance of the class which has actual values. The code for defining or creating an object is illustrated below.