'Python Class Quest [closed]

Hey guys i have a python Question The Problem says Define the method object inc_num_kids() for PersonInfo. inc_num_kids increments the member data num_kids. Sample output for the given program: Kids: 0 New baby, kids now: 1

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

# FIXME: Write inc_num_kids(self)
def inc_num_kids(self,num):
    num=1
    self.num_kids+=num

person1 = PersonInfo()

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

I Have already tried writeing the method myself and i got an error saying personinfo has no attribute inc_num_kids what should i do?



Solution 1:[1]

You need to indent inc_num_kids into the PersonInfo class. Currently it is just a standalone function. Python is sensitive to indentation and scoping is done by level of indentation:

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

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

Solution 2:[2]

class PersonInfo:
    def __init__(self):
        self.num_kids = 0
    def inc_num_kids(self, num=1):
        self.num_kids += num

person1 = PersonInfo()

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Alfredo Romero