Methods का उपयोग
एक method एक subroutine है जिसका पहला argument वह object या class है जिस पर यह call हुआ था।
In this page:
Methods
$obj->method(args) call करना object की class में method lookup करता है और object को पहले argument की तरह pass करता है, जो conventionally $self में store होता है। class name पर एक call, जैसे Class->method, इसकी बजाय class name string pass करता है और class methods के लिए इस्तेमाल होता है। क्योंकि arguments बस @_ हैं, methods अक्सर my ($self, @args) = @_; से शुरू होते हैं।
Note:
आप एक variable में stored नाम वाला method $obj->$method_name() से call कर सकते हैं।
उदाहरण: Methods
use strict;
use warnings;
package Counter;
sub new {
my $class = shift;
return bless { value => 0 }, $class;
}
sub increment {
my $self = shift;
$self->{value}++;
return $self;
}
sub value { my $self = shift; return $self->{value}; }
sub describe { my $class = shift; return "I am the class $class"; }
package main;
my $c = Counter->new;
$c->increment;
$c->increment->increment;
print "value: ", $c->value, "\n";
print Counter->describe, "\n";
my $method = "value";
print "dynamic call: ", $c->$method(), "\n";
# Output:
# value: 3
# I am the class Counter
# dynamic call: 3
Login to try C/C++/Java/PHP code in the editor
आम गलतियां
- @_ से $self shift करना भूल जाना
- एक method को plain function की तरह call करना ताकि $self missing हो
- किसी ऐसी चीज़ पर -> इस्तेमाल करना जो एक object या class name न हो
चैप्टर सारांश
- Methods invocant पहले receive करते हैं
- $self object hold करता है
- Class->method class name pass करता है
- $obj->$name() नाम से एक method call करता है
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: