While studying python, I couldn't catch up with how to write a class at once, so I output it and fix it.
--Class: A recipe for creating "things" in programming
--Instance: "Things" generated based on the recipe
To work with a class, you need to declare it.
sample.py
#Class declaration
class SampleClass():
Functions can be defined in the class. A function defined in a class is called a ** method **.
The method definition method is the same as a normal function, but self is used as the first argument.
sample.py
#Class declaration
class SampleClass():
def hello(self):
print("Hello World!")
Various information can be defined in the instance. Let's take an example of an item that is likely to be sold at a greengrocer. The following program outputs the name of the home appliance. You can use instance variables by setting "instance.instance variable name".
yaoyaclass.py
#Class declaration
class YaoyaItem():
def vegetable(self):
print(self.name)
#Assign the value of YaoyaItem class
yaoyaitem1 = YaoyaItem()
#Added information that the name of yaoyaitem1 is "radish"
yaoyaitem1.name = "Radish"
#Call the method defined in the class
yaoyaitem1.vegetable()
The vegetable method is called and the following result is obtained
Radish
If the method has arguments, write the argument names after the second argument.
yaoyaclass.py
#Class declaration
class YaoyaItem():
def payment(self,count):
#Set the total amount in the return value
return total_price = self.price * count
#Assign the value of YaoyaItem class
yaoyaitem1 = YaoyaItem()
yaoyaitem1.name = "Apple"
yaoyaitem1.price = 50
#Substitute 4 for count of the second argument
result = yaoyaitem1.payment(4)
print(yaoyaitem1.name+"I bought 4 pieces. total"+str(result)+It's a yen)
The result is displayed as below.
I bought 4 apples. 200 yen in total
I wrote it for the time being, but I wonder if it has taken root a little.
Recommended Posts