On 09/07/17 00:03, Evuraan wrote:

> I was hoping to learn when to use classmethod and when to use property.
> They both seem similar (to me at least..), what's the pythonic way to
> choose between them?

In fact they do completely different things.

A property is a field of an object that you access via a getter or
setter method but use a syntax that looks like direct access to the
field. This allows you to implement data validity rules when setting the
data, or to restrict data access in the getter for example.

You can even create read-only or write-only properties by omitting
one or other of the get/set methods. The pythonic way is to allow
direct access to the data if you have no need of special processing.
If you do need to limit access in some way create a property.

A classmethod by contrast is a method that applies to the class as
a whole rather than the individual instances. You access a normal
method via an instance of the class:

foo = Foo()  # create instance
x = foo.bar()   # call instance method bar()

A class method is accessed via the class, no instance is needed:

y = Foo.baz()  # call class method baz()

It's possible, and even quite common, to have a classmethod being
used when no instances exist at all. This is especially so in
languages like Java, whereas in Python those cases are more
often dealt with by creating a vanilla function in a module.

Typical use cases for class methods include factory methods
to create instances in special cases - for example loading
a specific instance from a database given some arbitrary
criteria. Or it could be that a class keeps a list of all
existing instances and a classmethod reports how many
instances exist. There are many other such cases.

[Note: What is confusing is the difference between staticmethod and
classmethod. Those two are similar but subtly different and I
recommend ignoring staticmethod and just use classmethod.]

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to