Home > Software engineering >  What is the purpose of the last two lines of code
What is the purpose of the last two lines of code

Time:04-04

I am trying to characterise my class with init but the website says I have to add the last two lines of code but I don't know what they do? Could someone explain? Code:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def myfunc(self):
        print("My awesome name is "   self.name)

p1 = Person("bob", 69)
p1.myfunc()

CodePudding user response:

It is pretty simple. Let's say you create a string.

a = "Hello"

This basically creates a new string object called a. Now you can use a variety of functions like .isdigit(), .isalnum() etc. These functions are basically the functions of the String class and when called, they perform the function in relation to the object they are associated with.
So Saying,

print(a.isalnum())

Would give True as the function is defined to check of the String object is alphanumeric.
In the same way,

p1 = Person("bob", 69) 
p1.myfunc()

First-line creates a new Person object with name='bob' and age=69. The second line then calls the function myfunc() in association with the Person p1 and executes with the attributes of p1 as its own local variables.

CodePudding user response:

The first chunk of code is defining a class. This says what the class should be called, what attributes it has, and defines its behaviour.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def myfunc(self):
        print("My awesome name is "   self.name)

Once those lines are run, the class exists in your session, but no instances of it do.

This creates an instance of the class:

p1 = Person("bob", 69)

And this line is that instance calling its method myfunc():

p1.myfunc()

CodePudding user response:

On:

p1 = Person("bob", 69)

Here you're creating an instance of Person with bob as name and 69 as age. This instance is assigned to the variable p1.

Since the variable p1 refers to an object Person, it has a method called myfunc, that you call when you run the last line to print My awesome name is bob.

  • Related