Creating a method object

Creating a method object. Define the method object inc_num_kids() for PersonInfo. inc_num_kids increments the member data num_kids. Sample output for the given program with one call to inc_num_kids(): Kids: 0 New baby, kids now: 1 1 class PersonInfo: 2 3 def init(self): 4 self.num_kids = 0 5 6 # FIXME: Write inc_num_kids(self) 7 8 person1 = PersonInfo() 9 10 print(‘Kids:’, person1.num_kids) 11 person1.inc_num_kids() 12 print(‘New baby, kids now:’, person1.num_kids)

The Correct Answer and Explanation is:

ere is the correct version of the program, including the inc_num_kids() method and a corrected constructor:

pythonCopyEditclass PersonInfo:
    def __init__(self):
        self.num_kids = 0

    def inc_num_kids(self):
        self.num_kids += 1

person1 = PersonInfo()

print('Kids:', person1.num_kids)
person1.inc_num_kids()
print('New baby, kids now:', person1.num_kids)

Explanation (Book Style – ~300 Words):

In object-oriented programming (OOP), a method is a function that belongs to a class. It operates on data that belongs to the object created from that class. In the given program, we are working with a class called PersonInfo. This class models a person’s information and currently keeps track of the number of children (kids) a person has.

First, the special method __init__() is used to initialize a new object of the class. It is known as the constructor and is called automatically when an object is created. Inside __init__(), we define and initialize the data member num_kids to 0, meaning that a new person starts with zero kids.

The next step is to define a method called inc_num_kids(). This method will increase the num_kids attribute by 1 every time it is called. The keyword self is used within the class to refer to the current object. Therefore, self.num_kids += 1 means: increase the number of kids for the current object by 1.

In the main part of the program, we create an instance of the PersonInfo class using person1 = PersonInfo(). This calls the constructor and sets person1.num_kids to 0. The first print() statement confirms this by outputting “Kids: 0”.

Next, we call the method person1.inc_num_kids(). This increases person1.num_kids from 0 to 1. The second print() statement then confirms this change by outputting “New baby, kids now: 1”.

This example demonstrates how class methods can be used to modify object data in a structured and encapsulated way.

Scroll to Top