There are cases where methods with self and methods with self are mixed when defining a function in a class.
Each has a name and its use and calling method are different.
item | with self | No self |
---|---|---|
Method name | Class method | Instance method |
Target | Whole class | Instance only |
Method name example | self.hello1 | hello2 |
Example of how to call | name of the class.hello1 | name of the class.new.hello2 |
python
class TestClass
#Method with self
def self.hello1
p "self hello 1"
end
#Method without self
def hello2
p "hello 2"
end
end
In the class TestClass
, there are the following two methods.
--self.hello1
: Class method
--hello2
: Instance method
Each calling method is as follows.
How to call a method with self
Call a method with self
TestClass.hello1
=> "self hello 1"
#Or
::TestClass.hello1
=> "self hello 1"
It is OK if you execute the method directly with the class name as an object.
In order to call the selfless method, you need to ** create an instance and execute the method on the created instance **.
Call the self-less method
#Create and assign an instance
inst = TestClass.new
inst.hello2
=> "hello 2"
#or
#Create an instance and run it directly
TestClass.new.hello2
=> "hello 2"
** Instance methods are valid only for that instance **, so they are often used for product generation and person generation.
Class definition
class Product
######Whole class
#Class variable (initialized with initial value 0)
@@product_ttl_num = 0
#Class method
def self.ttl_num
p "Number of products:#{@@product_ttl_num}"
end
#####For each instance
#Method to be executed automatically when instantiating
def initialize(category)
@product_category= category
@product_list = []
end
#Instance method (for addition)
def add(name)
@product_list.push name
#Add 1 to class variable
@@product_ttl_num += 1
end
end
That's all for class definition. Then create an instance.
Create an instance
##Instance generation (phone category)
phone = Product.new(phone)
#Instance method execution
phone.add("iphone6s")
phone.add("iphone12pro")
##Instance generation(codes category)
codes = Product.new(codes)
#Instance method execution
phone.add("USB typeC")
phone.add("USB3.0")
Create two instances of phone and codes, and register a total of four products, two for each.
Execution of class method
#Class method execution
Product.ttl_num
=> "Number of products: 4"
When you execute the class method, you can get the total score of the products of all instances.