A class is a blueprint for creating a thing, and an instance is that thing.
Prepare a class ⇨ Create an instance from a class ⇨ Add information to an instance
** class Class name: ** The contents of the class are indented in the line after "class class name:" Write ** pass ** if you don't need to add any processing
You can call a class with ** class name () ** and create a new instance using the class By setting ** variable name = class name () **, the generated instance can be assigned to the variable.
Add information that name is banana to fruit1 by setting fruit.name = "banana" as shown in the code below. The name at this time is called ** instance variable ** By setting ** instance.instance variable name **, the value of that instance variable can be used.
python.py
class Fruits:
pass
fruit1 = Fruits()
fruit1.name = "banana"
You can define a function in a class (this function is called ** method **) The method definition method is the same as a normal function, but you need to add self to the first argument. The method defined in the class is called to be used for the instance. Specifically, the method can be called by setting ** instance.method name () **. The instance that called the method is assigned to "self" specified in the first argument of the instance method. Instances have "instance variables" as information and "instance methods" as processing
The init method can be defined like any other instance and will be called automatically immediately after the instance is created. You can use this method to create an instance and assign a value to an instance variable at the same time. You can also pass arguments and change the value for each instance
By setting ** from module name import class name **, the specified class in the module can be read directly.
Recommended Posts