Paiza Python Primer 8: Understanding Classes

Python3 is completely free on Paiza, so I summarized it.

Introduction to Paiza Python3

01: Let's understand the class

What is an object?

Simply put, a set of variables and functions

Player object

--Variables

name="paiza"
Profession="Wizard"
Physical fitness="120"

--Function

Attack processing()
Move processing()

Functions organized in objects → methods

How to use objects

--Create an object from a class and use it --Class: Object blueprint --Object: Generate from class

Player class

name
attack()

Create a Player object from the Player class

name="paiza"
attack()

name="python"
attack()

name="dragon"
attack()

An object created from a class is called an instance.

Benefits of objects

--Variables and methods set

Hard to get bugs

--Separated into classes and objects

Easy to reuse Easy to classify ↓ Numerous libraries / frameworks are based on classes

02: Let's create a class

lesson.py


#Capitalize the beginning of the class name
#1.Specify the class name Plyaer in the class
class Plyaer:
    #2.Methods of the class(Write a function)
    def walk(self):
        print("The brave was walking in the wilderness")

#3.Create an object using the class name
#Let's assign the created object to a variable
plyaer1=Plyaer()
#Variable name.You can also call the object created by the method name
plyaer1.walk()

#You can also assign an object to a variable

#class
class Player:

#Properties and methods

    def walk(self):
        print("The brave was walking in the wilderness")

    #Increased methods
    def attack(self, enemy):
        print("The hero" + enemy + "Attacked")

#object
player1=Player()
player1.walk()
player1.attack("Slime")

The brave was walking in the wilderness
The hero attacked the slime

#An object is a collection of methods and properties of a class.

Exercise

  1. Let's create an object from a class

lesson.py



class Greeting:
    def say_hello(self):
        print("hello paiza")

#Below this, add the code you need
greeting=Greeting()
greeting.say_hello()

  1. Let's define a method in the class

class Plyaer:

lesson.py



class Greeting:
    #Below this, add the code you need
    def say_hello(self):
        print("hello python")

paiza = Greeting()
paiza.say_hello()

  1. Find the difference

There was no:

lesson.py



class Greeting:
    def say_hello(self):
        print("hello paiza")

paiza = Greeting()
paiza.say_hello()

03: Let's manage variables in class

class Plyaer:

lesson.py



class Player:
    #constructor
    #When creating an object from a class
    #First method called
    #Add a variable called job to Plyaerclass
    def __init__(self,job):
    #Call it an instance variable
        self.job=job

    def walk(self):
        print(self.job+"Was walking in the wilderness")

player1=Player("Warrior")
player1.walk()


player2=Player("Wizard")
player2.walk()

#The player1 object continues to have the value of a warrior
player1.walk()

output


The warrior was walking in the wilderness
The witch was walking in the wilderness
The warrior was walking in the wilderness
#self.job is an instance variable

#A variable that an object has
#Instance variables are as long as the object exists
#The value is saved
        self.job=job

#What is self
#Arguments required when using instance variables
#In python, it is the first argument of the method in the class
#The object itself used to call the method is passed
#self is English meaning myself,
#Refers to the object used to call the method
#When you call the work method of player1, selfjob
#Call the job variable for player1
#When you call the work method of player2
#Calling the job variable for player2
 def __init__(self,job):

Exercise

  1. Let's create an object from a class

lesson.py


#Let's create an object from a class

class Greeting:
    def __init__(self, name):
        self.name = name

    def say_hello(self):
        print("hello " + self.name)

#Below this, describe the necessary processing

greeting=Greeting("paiza")
greeting.say_hello()

output

hello paiza

  1. Let's add an instance variable to the class

lesson.py



class Greeting:
    def __init__(self,name):

        self.name=name


    def say_hello(self):
        print("hello " + self.name)

paiza = Greeting("paiza")
paiza.say_hello()


hello paiza

  1. Find the difference class Plyaer:

lesson.py



class Greeting:
    def __init__(self, name):
        self.name = name

    def say_hello(self):
        print("hello " + self.name)

paiza = Greeting("paiza")
paiza.say_hello()

04: Create an RPG enemy class

class Plyaer:

lesson.py



review
def attack(enemy):
    print(enemy + "Attacked the brave")

attack("Slime")


'''
Make an Enemy class
class Enemy:
    def__init__(self,name)
    self.name=name
'''
#Make an Enemy class
'''
class Enemy:
    def__init__(self,name)
    self.name=name
'''
class Enemy:
    def __init__(self,name):
        self.name = name

    def attack(self):
    #enemy→self.nane
        print(self.name + "Attacked the brave")

#Create an object from the enemy class
slime=Enemy("Slime")
slime.attack()

output
Slime attacked the brave

lesson.py



#Make an Enemy class

class Enemy:
    def __init__(self,name):
        self.name = name

    def attack(self):
        print(self.name + "Attacked the brave")

#List up to create multiple enemies
enemies=[]
enemies.append(Enemy("Slime"))
enemies.append(Enemy("monster"))
enemies.append(Enemy("Dragon"))

#Use a for statement to output
for enemy in enemies:
    enemy.attack()

output
Slime attacked the brave
The monster attacked the hero
The dragon attacked the hero

#English class has the meaning of classification
#Slime, monster, and dragon are enemies in the same Enemy class, so you can use the common attack method.

#English instance has the meaning of an example
#The enemy class defines the classification of enemies and creates slimes and monsters as objects.
#The created list is assigned to the enemies list with the for statement.

Exercise

RPG attack scene

lesson.py



class Player:
    def __init__(self, name):
        self.name = name

    def attack(self, enemy):
        print(self.name + "Is" + enemy + "Attacked")

team = []
team.append(Player("Brave"))
team.append(Player("Warrior"))
team.append(Player("Wizard"))

for player in team:
     player.attack("Slime")

05: Let's create a method with arguments and return value

lesson.py


class Item:
    def __init__(self,price,quantity):
        self.price=price
        self.quantity=quantity

    def total(self):
        return self.price * self.quantity
apple=Item(120,15)
print("The total amount is" + str(apple.total()) + "It's a yen")
#total=apple.total(),str(total)
#Even if it is OK → The return value of the total method is output by print
apple=Item(120,15)
print("The total amount is" + str(total) + "It's a yen")
orange=Item(85,32)
print("The total amount is"+str(orange.total())+"It's a yen")
output
The total amount is 1800 yen
The total amount is 1800 yen
The total amount is 2720 yen

lesson.py


How to make the amount including tax?
class Item:
    tax=1.08
#Use the classes variable for which you want to create sales tax,
#Created from that class, unlike instance variables
#Variables that can be used in all objects

    def __init__(self,price,quantity):
        self.price=price
        self.quantity=quantity

    def total(self):
        #Int to truncate after the decimal point
        #For calculating sales tax`Item.tax
        return int(self.price * self.quantity*Item.tax)
apple=Item(120,15)
total=apple.total()
print("The total amount is" + str(total) + "It's a yen")
orange=Item(85,32)
print("The total amount is"+str(orange.total())+"It's a yen")

The total amount is 1944 yen
The total amount is 2937 yen

Exercise

  1. Call the student method

lesson.py



 class Gakusei:
    def __init__(self, kokugo, sansu):
        self.kokugo = kokugo
        self.sansu  = sansu
    def sum(self):
        return str(self.kokugo + self.sansu)
#Below this, describe the necessary processing
yamada = Gakusei(70, 43)
print("The total is" +str(yamada.sum()) +"Is a point")
  1. Make a student method

lesson.py


class Gakusei:
    def __init__(self, kokugo, sansu):
        self.kokugo = kokugo
        self.sansu  = sansu
    #Below this, write a sum method that returns the total score as a return value.
    def sum(self):
        return str(self.kokugo + self.sansu)
yamada = Gakusei(70, 43)
print("The total is" + str(yamada.sum()) + "Is a point")

06: String and list methods

  1. Execute the method on the string

lesson.py


text= "pYthon"
print(text)
#Capitalize the acronym
print(text.capitalize())
#All capital letters
print(text.upper())
players="Brave,Warrior,Wizard,Ninja"
#List strings
#The split method is the character specified by the argument
#A method that splits a string and returns a list
list=players.split(",")
print(list)
#Methods available in the list
#The element specified by the argument can be deleted from the list
list.remove("Ninja")
print(list)
list.append("Kirishima")
print(list)
pYthon
Python
PYTHON
['Brave', 'Warrior', 'Wizard', 'Ninja']
['Brave', 'Warrior', 'Wizard']
['Brave', 'Warrior', 'Wizard', 'Kirishima']

Exercise

lesson.py


input
testcase
msg = input()
#Below this, describe the process to display whether msg is all lowercase.
print(msg.islower())
output
True
  1. Execute the method on the list

lesson.py


team = ["Brave", "Warrior", "Wizard", "Ninja"]
#Below this, add "thief" to index 3 and describe the process to display the list.
team.insert(3, "Thieves")
print(team)

07: Let's understand access restrictions

lesson.py


class Player:
    def __init__(self, job, weapon):
        self.job = job
        self.weapon = weapon
    def walk(self):
        print(self.job + "Was walking in the wilderness")

    #Prepend an underscore to the method name
    #__attack
    def __attack(self, enemy):
        print(self.weapon + "so" + enemy + "To attack")
    #__attack
        self.__attack("Slime")
player1 = Player("Warrior", "sword")
player1.walk()
#__You can't do this outside of the attack class
#player1.__attack("Slime")
__.weapon
print(player1.weapon)
#Underscore before variable name(__)If you add two
#Become a variable that can only be called in the class
#This is called a private variable or private property.

lesson.py


class Player:
    def __init__(self, job, weapon):
        self.job = job
        #__weapon
        self.__weapon = weapon
    def walk(self):
        print(self.job + "Was walking in the wilderness")

    def __attack(self, enemy):
        #__weapon
        print(self.__weapon + "so" + enemy + "To attack")
        self.__attack("Slime")
player1 = Player("Warrior", "sword")
player1.walk()
#__weapon
print(player1.__weapon)
#Underscore before variable name(__)If you add two
#Become a variable that can only be called in the class
#This is called a private variable or private property.

Exercise

"Execute a method on a string"

lesson.py


class Greeting:
    def __init__(self, name):
        self.__name = name
    def say_hello(self):
    #Add two underscores here
        print("hello " + self.__name)
paiza = Greeting("paiza")
paiza.say_hello()

Recommended Posts

Paiza Python Primer 8: Understanding Classes
Paiza Python Primer 7: Understanding Functions
Paiza Python Primer 1 Learn Programming
Paiza Python Primer 4: List Basics
Paiza Python Primer 5: Basics of Dictionaries
Paiza Python Primer 3: Learn Loop Processing
Understanding Python Coroutine
Understanding python self
Python classes are slow
Python basic course (13 classes)
Python Tkinter Primer Note
Paiza Python Primer 2: Learn Conditional Branching and Comparison Operators
O'Reilly python3 Primer Learning Notes
About python objects and classes
Python classes learned in chemoinformatics
Full understanding of Python debugging
That Python code has no classes ...
Python ABC-Abstract Classes and Duck Typing
Python and DB: Understanding DBI cursors
Python: A Note About Classes 1 "Abstract"
What was surprising about Python classes
[Python] About Executor and Future classes
[Python] Understanding the potential_field_planning of Python Robotics
Python classes and instances, instance methods
[Road to Intermediate] Understanding Python Properties
Understanding python classes Struggle (2) Work That's not all, right? _ About class inheritance