Python code basics -object,class

reference:w3schools.com/python/python_classes.asp

Question: Insert a function that prints a greeting, and execute it on the v1 object:

Steps: -define class -define function -define object
-assign on object

First, we have to initialize the class (we give it the name 'Myclass' ) . Then,use the word 'def init' to define a function under the class. Pass the parameters (self,name,age) into the function.

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

Then, define another function , 'myfunc' to pass the name, age and greeting before assigning it to an object. We use 'str(self.age))' because to convert int type to string as python can only concatenate str (not "int") to string.

  def myfunc(self):
    print("Hi, you are "+ self.name+ " age  "+str(self.age))

Create a new object, v1, and pass the class 'Myclass' into v1.

v1=Myclass("Aaron",12)

The, we just call function 'myfunc' and pass it to object 'v1'.

v1.myfunc()

Then, the output will be:

Hi, you are Aaron age  12

Here is the full code:

#https://www.w3schools.com/python/python_classes.asp

# Insert a function that prints a greeting, and execute it on the p1 object:

# create:
# -class
# -object  
# -define function
# -assign on object

# define class,function
class Myclass:
  def  __init__(self, name,age):
    self.name=name
    self.age=age

  def myfunc(self):
    print("Hi, you are "+ self.name+ " age  "+str(self.age))

# create object,assign on object
v1=Myclass("Aaron",12)
v1.myfunc()