Should I Use Class Method or Instance Method, and Why

Why use a classmethod over an Instance method in python

In your second example, you've hard-coded the name and age into the class. If name and age are indeed properties of the class and not a specific instance of the class, than using a class method makes sense. However, if your class was something like Human of which there are many instances with different names and ages, then it wouldn't be possible to create a class method to access the unique names and ages of the specific instance. In that case, you would want to use an instance method.

In general:

  • If you want to access a property of a class as a whole, and not the property of a specific instance of that class, use a class method.
  • If you want to access/modify a property associated with a specific instance of the class, then you will want to use an instance method.

is there any advantage when use class method instead of instance method?

My explanation is a little different.

Instance methods are sent to an INSTANCE of a class. An instance of a class is a concrete thing. It has state data that persists for the life of the object. When you send a message to an object, it can use that state data to do things, and it can remember information for later.

Class methods are sent to the class as a whole. A class is a more abstract concept. Classes do not save state data, at least in Objective C (In other languages like C++, there are class variables that belong to the entire class, but Objective C does not have class variables.)

Lets move to an example of a car factory

The car factory is the class. The car class has a class method buildCar. The buildCar method takes parameters that tell what color the car should be, how big the engine should be, what options it should have, etc. You sent the car factory (the class) a buildCar message, and it creates and returns an instance of that class (the car factory builds you a car and gives it to you.)

Once you've created a car, that particular car has state variables that store things like the channel on the radio, the amount of gas left in the tank, the milage ("kilometerage"?) on the odometer, the wear level on the brakes, etc. Different cars will have different values for those variables.

You can ask an individual car how much gas is left in it's tank. (instance method.) Car A might have a full tank, and car B might be nearly empty.

However, it would not make sense to ask the car factory how much gas it has in the tank. A car factory doesn't have a gas tank. However, you could ask a car factory about the types of cars that it can build and the options for those cars. That is static information that always holds true for that car factory.

In addition to "factory methods" (e.g. build me a car), you can use class methods like you use functions in a procedural language. A class method is self-contained. You pass all the parameters into the method that you need in order to do whatever task is required, and you get back a single result (or no result for a void class method.) Once the class method is done executing, there is no state data left to record what happened.

Purpose of Instance Methods vs. Class Methods in Objective-C

Generally speaking, you should create instance methods when you need code that operates on a specific instance of an object. You create a class method when you need to do something that involves that class in general but probably doesn't operate on any specific objects of that class.

In practice, you will find that nearly all of your methods should be instance methods. Just take a look at any existing Objective-C class like NSString, NSArray, UIView, etc. and you'll see that the vast majority of their methods are instance methods. The most common use of class methods (again, look at the classes I mentioned) are for convenience constructors that return autorelease objects, or singleton accessors.

Consider the length method in NSString. Why is this an instance method and not a class method? It is an instance method because it only makes sense to ask a specific instance of NSString what its length is. Asking NSString in general for a length (i.e. if length was a class method) wouldn't make any sense.

On the other hand, let's say that we want to add a method to NSNumber that will return the maximum integer value that can be stored on a given system. In this case, it should be a class method because we're just asking a general question of NSNumber that is independent of any specific instance.

Class methods vs instance methods

I don't know about generally, but I remember measuring for some application some time ago, and static methods were indeed faster.

From a design standpoint I would argue that any method than can sensibly be static (meaning without explicitly passing an instance as parameter or something like that), should be.

Difference between class and instance methods

Instance methods

When creating an instance method, the first parameter is always self.
You can name it anything you want, but the meaning will always be the same, and you should use self since it's the naming convention.
self is (usually) passed hiddenly when calling an instance method; it represents the instance calling the method.

Here's an example of a class called Inst that has an instance method called introduce():

class Inst:

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

def introduce(self):
print("Hello, I am %s, and my name is " %(self, self.name))

Now to call this method, we first need to create an instance of our class.
Once we have an instance, we can call introduce() on it, and the instance will automatically be passed as self:

myinst = Inst("Test Instance")
otherinst = Inst("An other instance")
myinst.introduce()
# outputs: Hello, I am <Inst object at x>, and my name is Test Instance
otherinst.introduce()
# outputs: Hello, I am <Inst object at y>, and my name is An other instance

As you see, we're not passing the parameter self. It gets hiddenly passed with the period operator. We're calling Inst class's instance method introduce, with the parameter of myinst or otherinst.
This means that we can call Inst.introduce(myinst) and get the exact same result.



Class methods

The idea of a class method is very similar to an instance method, only difference being that instead of passing the instance hiddenly as a first parameter, we're now passing the class itself as a first parameter.

class Cls:

@classmethod
def introduce(cls):
print("Hello, I am %s!" %cls)

Since we're passing only a class to the method, no instance is involved.

This means that we don't need an instance at all, and we call the class method as if it was a static function:

 Cls.introduce() # same as Cls.introduce(Cls)
# outputs: Hello, I am <class 'Cls'>

Notice that again Cls is passed hiddenly, so we could also say Cls.introduce(Inst) and get output "Hello, I am <class 'Inst'>.

This is particularly useful when we're inheriting a class from Cls:

class SubCls(Cls):
pass

SubCls.introduce()
# outputs: Hello, I am <class 'SubCls'>

Should I use class method or instance method, and why?

As their name suggests, instance methods on a model should be used for logic/operations that relate to a specific instance of a user (the one on which the method is called.) So you could think of setting the default company for a user as an instance method on User. Class methods are for things which don't operate on an individual instance of a model or for cases where you don't have the instance available to you. e.g. you might have a class method to tidy up your database such as User.purge_expired_users which would not apply to an individual user object.

e.g.

class User
def set_default_company(company)
exists = DefaultCompany.find(self.id)
if exists
exists.update_attributes(company: company)
else
DefaultCompany.create(company: company, user: self)
end
end
end

then your controller method would look like:

def create
@company = Company.new(params[:company])

if @company.save
if params[:default_company]
current_user.set_default_company @company
end
flash[:notice] = "Company was successfully created."
redirect_to @company
else
redirect_to new_company_path
end
end

Alternatively, you could think of the relationship from the other perspective and put an instance method on Company e.g. company.set_as_default_for(user).

Swift.... Class method vs. Instance method

If you're asking a question you should reduce your code to a minimum, discarding unnecessary details.

You probably want something like this:

class MyClass {
let x = MyClass.getStuff()

static func getStuff() -> Int {
return 0
}
}

However your method getWallImages() can't do something like this, because it's returning the result asynchronous, which means you get the result much later after the function has returned.

You could do something like this though (this is how I'd be doing it):

class MyClass {
var x : Int? {
didSet {
if let x = x {
// Do something with x, here it's assigned
} else {
// x was set to nil, something failed
}
}
}

init() {
getStuffAsynchronous()
}

func getStuffAsynchronous() {
// Do your query stuff here, assign x to your objects to invoke the didSet
x = 0

// If it fails somehow, assign set x to nil
// if fail {
// x = nil
// }
}
}

What is the difference between class and instance methods?

Like most of the other answers have said, instance methods use an instance of a class, whereas a class method can be used with just the class name. In Objective-C they are defined thusly:

@interface MyClass : NSObject

+ (void)aClassMethod;
- (void)anInstanceMethod;

@end

They could then be used like so:

[MyClass aClassMethod];

MyClass *object = [[MyClass alloc] init];
[object anInstanceMethod];

Some real world examples of class methods are the convenience methods on many Foundation classes like NSString's +stringWithFormat: or NSArray's +arrayWithArray:. An instance method would be NSArray's -count method.

What is the purpose of class methods?

Class methods are for when you need to have methods that aren't specific to any particular instance, but still involve the class in some way. The most interesting thing about them is that they can be overridden by subclasses, something that's simply not possible in Java's static methods or Python's module-level functions.

If you have a class MyClass, and a module-level function that operates on MyClass (factory, dependency injection stub, etc), make it a classmethod. Then it'll be available to subclasses.

difference between class method , instance method , instance variable , class variable?

First take a look at this diagram:

from "Metaprogramming Ruby" book

You can rightly say that “obj has a method called my_method( ),” meaning that you’re able to call obj.my_method(). By contrast, you shouldn’t say that “MyClass has a method named my_method().” That would be confusing, because it would imply that you’re able to call MyClass.my_method() as if it were a class method.

To remove the ambiguity, you should say that my_method() is an instance method (not just “a method”) of MyClass, meaning that it’s defined in MyClass, and you actually need an instance of MyClass to call it. It’s the same method, but when you talk about the class, you call it an instance method, and when you talk about the object, you simply call it a method. Remember this distinction, and you won’t get confused when writing introspective code like this:

String.instance_methods == "abc".methods # => true String.methods == "abc".methods # => false

an object’s instance variables live in the object itself, and an object’s methods live in the object’s class. That’s why objects of the same class share methods but don’t share instance variables.



Related Topics



Leave a reply



Submit