Page 410 - Computer_Science_F5
P. 410

(a) Class attributes and methods         object creation. Constructor parameters
              Attributes are variables associated with   are used to initialise instance attributes
              the class or its instances, storing data   with specific values.
              related to the class. Methods are functions   (c) Instance and class methods:        Chapter Six: Object oriented programming with Python
              defined within a class, performing actions
          FOR ONLINE READING ONLY
              or providing functionality associated with   Instance methods are defined with the
              the class. Instance attributes are specific   “self” parameter and operate on individual
              to each object, while class attributes are   object instances.  Class methods are
              shared among all instances.              defined with the @classmethod decorator
                                                       and operate on the class itself rather than
              (b) Constructor method (init)            instances.

              The  init  method is a special  method
              called  when an object  is created.  It  The  following program  example  6.2
              initializes  the object›s  attributes  and  demonstrate how a class  and object are
              performs any necessary setup during  created.


                       Program Example 6.2:
               Program codes to demonstrate creating class and object

                   class Dog:
                       # Class attribute
                       species = “Canine”
                       # Constructor method
                       def __init__(self, name, age):
                           self.name = name  # Instance attribute
                           self.age = age
                       # Instance method
                       def description(self):
                           return f”{self.name} is {self.age} years old”
                       # Class method
                       @classmethod
                       def bark(cls):
                           return “Woof!”
                   # Creating objects of the Dog class
                   dog1 = Dog(“Buddy”, 3)
                   dog2 = Dog(“Max”, 5)

                   # Accessing object attributes and methods
                   print(dog1.description())  # Output: Buddy is 3 years old
                   print(dog2.description())  # Output: Max is 5 years old
                   print(Dog.bark())          # Output: Woof!



                                                    401
               Student’s Book  Form Five



     Computer Science Form 5.indd   401                                                     23/07/2024   12:34
   405   406   407   408   409   410   411   412   413   414   415