bit.ly/3fvqmF2
Welcome to 60 seconds to code where I show you how to code in 60 seconds or less.
Today you will learn about classes. A class a blueprint that packages properties and functions into a single object. Think of it as a blueprint with which you can create multiple objects. For example, with a house blueprint, you can create multiple houses or with a car blueprint, you can create multiple cars.
Step 1- Create a file called classes.py and in line 1 type class Person: in line 2 type def __init__(self, name, age): in line 2 type self.name = name and in line 3 type self.age = age. Self is an argument that is used to point to the current particular object you are referring to and init is a special method that is required to initialize all values for objects when they are created.
Step 2 – In line 5 type def get_name(self): and in line 6 type return self.name. In line 7 type def get_age(self): and in line 8 type return self.age
Step 3 – In line 9, type def say_hi(self): and in line 10 type return "Hi, my name is " + self.name + " and I am " + str(self.age) + " years old"
Step 4 – In line 11 type jack = Person("Jack",21) and in line 12 type elvis = Person ("Elvis", 42)
Step 5 – In line 13 type print(jack.get_name()) line 14 type print(elvis.get_age()) and on line 15 type print(jack.say_hi())
Step 6 – Set a break point in line 6 and line 8 and run the file. When the breakpoint is triggered, expand the local windows and see what object the self keyword is referring to. Click continue to go to the next breakpoint.
The code is available in a link in the description.
Congratulations, you have learned about classes. For your homework, create another function called set_age for the person class that sets the persons age to a specified number that you pass in to the function. You can also set the age of an object directly by using the dot notation such as jack.age = 22 but why might that not be a good idea?
Learn #classes and creating #objects in #python #100DaysOfCode #301DaysofCode #60secondstocode
bit.ly/3fvqmF2
コメント