Difference Between Type Method and Type Instance Method, etc

Difference between type method and type instance method, etc?

In Swift, types are either named types or compound types. Named types include classes, structures, enumerations, and protocols. In addition to user-defined named types, Swift defines many named types such as arrays, dictionaries, and optional values. (Let's ignore compound types for now since it doesn't directly pertain to your question.)

To answer your questions, suppose that I create a user defined class called Circle (this is just an example):

class Circle {

static let PI = 3.14

var radius: Double

init(radius: Double) {
self.radius = radius
}

// Returns the area of this circle
func area() {
return PI * radius
}

// Ridiculous class method for demonstration purposes
static func printTypeName() {
println("Circle")
}
}
  1. I'm confused on the difference between a "type instance method"
    (if such exists, correct me if I'm wrong) and a type method?

As mentioned earlier, a type refers to a class, structure, enumeration, protocol, and compound types. In my example above, I use a class called Circle to define a type.

If I want to construct an individual object of the Circle class then I would be creating an instance. For example:

let myCircleInstance = Circle(radius: 4.5)
let anotherCircleInstance = Circle(radius: 23.1)

The above are objects or instances of Circle. Now I can call instance methods on them directly. The instance method defined in my class is area.

let areaOfMyCircleInstance = myCircleInstance.area()

Now, a type method is a method that can be called directly on the type without creating an instance of that type.

For example:

Circle.printTypeName()

Notice that there is a static qualifier before the func. This indicates that it pertains to the type directly and not to an instance of the type.


  1. Difference between class method and instance method?

See the explanation above.


  1. Difference between type property and instance property(if such
    exists, sorry I'm very confused on Type Properties subject)?

This is a similar explanation to the one in your question one except that instead of applying to methods, it applies to the properties (i.e., attributes, variables) of the type.

In my Circle example, the properties are defined as:

static let PI = 3.14
var radius: Double

The property PI is a type property; it may be accessed directly by the type

Circle.PI

The property radius is an instance property of the type; it may be accessed by an instance of the type. Using the variables we created earlier:

// I can do this; it will be 4.5
myCircleInstance.radius

// And this; it will be 23.1
anotherCircleInstance.radius

// But I CANNOT do this because radius is an instance property!
Circle.radius

  1. Lastly, Do class properties exist in swift?

Absolutely! Read my explanation to your question 3 above. The PI property in my example is an example of a class property.

References:

  • Swift Language Reference - Types
  • Swift Language Reference - Properties
  • Swift Language Reference - Methods

The difference between Swift's instance methods and type methods

A class method is useful when you want to connect some kind of functionality to a class without forcing the client to instantiate that class, and when a method doesn't depend on the state of a particular object.

In an object-oriented approach to programming they are often used in place of traditional utility-style functions, which take some sort of input and return output without referencing a particular object, e.g., an HTTP routing system with class methods "Post" and "Get" that takes a url and query parameters as arguments and sends a request to the server. These functions are useful across a range of different classes and don't necessarily need to be represented by an underlying instance variable.

They can also be used to include comparison functions where both objects are of the same class. Say you're trying to calculate the dot product of two matrix objects--it doesn't make sense to prefer one object as the basis on which to compare the other and not the other way around--especially since calculation of a dot product has no consequences for either underlying matrix object. The preferred solution then is something like:

 class func dotProduct(a: Matrix, b: Matrix) -> Double

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'>

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 need of Class type method?

Here is the difference between class and instance method.

Class Method

  • You can use class method for your common functionality like validation,color from hex color,etc.. and used anywhere in project without creating instance of that class (called like utility class).

  • Class method indirectly said static method.

  • No need to create object of class for calling this type of method.

  • Class method starts with + in objective-c and class func in swift.

  • stringWithFormat is a class method of NSString class you can call directly using class name (not required to create object of NSString).

    int no = 5;
    NSString *str = [NSString stringWithFormat:@"Some String %d",no];

Instance Method

  • You create instance method for your specific functionality like setupView,etc.. and you have to create instance for calling it.

  • Instance method is a simple method within specific class.

  • Need to create object of class for calling this type of method.

  • Instance method starts with - in objective-c and func in swift.

  • isEqualToString is an instance method of NSString class you can call only using with NSString class object.

    NSString *str = @"some string";
    NSString *str2 = @"some string";
    Bool isEqual = [str isEqualToString:str2];

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 type , instance , class and object concepts

Quick Example

A class is the design specs for a MacbookPro, an instance is your MacbookPro specifically.

A type is just a class that defines your class, so that we can look at a blueprint and ask if design spec is MacbookProBlueprint. This is useful when we want meta-data about our classes (or other types). Think of a type as an Amazon.com entry, that would have lots of information about the MacbookPro such as processor speed and capabilities but not enough to actually build the object.

An object is your MacbookPro, or my car, or anything. Everything is an object which has implications larger than the scope of this question, but is fundamental nonetheless.

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.

What is the difference between using magic method of a class with following syntaxes in Python: method(member) and member.__method__()?

The __len__ magic method is supposed to return something, in this case, probably return self.quantity. You are getting the type error because your method implicitly returns None.

The idea of using these magic methods is to define behavior for commonly used functions like len(). If you call it using instance.__len__(), you are not utilizing the magic method, you are simply calling it like a regular instance method, which is why you don't see any error in that use case



Related Topics



Leave a reply



Submit