Top methods Questions

List of Tags
261
Joan Venge

Is it possible to have static methods in Python so I can call them without initializing a class, like:

ClassName.StaticMethod ( )
Answered By: dbr ( 343)

Yep, using the staticmethod decorator

class MyClass(object):
    @staticmethod
    def the_static_method(x):
        print x

MyClass.the_static_method(2) # outputs 2

Note that some code might use the old method of defining a static method, using staticmethod as a function rather than a decorator. This should only be used if you have to support ancient versions of Python (2.2 and 2.3)

class MyClass(object):
    def the_static_method(x):
        print x
    the_static_method = staticmethod(the_static_method)

MyClass.the_static_method(2) # outputs 2

This is entirely identical to the first example (using @staticmethod), just not using the nice decorator syntax

Finally, use staticmethod sparingly! There are very few situations where static-methods are necessary in Python, and I've seen them used many times where a separate "top-level" function would have been clearer.


Docs:

A static method does not receive an implicit first argument. To declare a static method, use this idiom:

class C:
    @staticmethod
    def f(arg1, arg2, ...): ...

The @staticmethod form is a function decorator – see the description of function definitions in Function definitions for details.

It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class.

Static methods in Python are similar to those found in Java or C++. For a more advanced concept, see classmethod().

For more information on static methods, consult the documentation on the standard type hierarchy in The standard type hierarchy.

New in version 2.2.

Changed in version 2.4: Function decorator syntax added.

I came across some Java code that had the following structure:

public MyParameterizedFunction(String param1, int param2)
{
    this(param1, param2, false);
}

public MyParameterizedFunction(String param1, int param2, boolean param3)
{
    //use all three parameters here
}

I know that in C++ I can assign a parameter a default value. For example:

void MyParameterizedFunction(String param1, int param2, bool param3=false);

Does Java support this kind of syntax? Are there any reasons why this two step syntax is preferable?

Answered By: Kathy Van Stone ( 138)

No, the structure you found is how Java handles it (i.e. with overloading instead of default parameters).

For constructors See Effective Java's Item 1 tip (Consider static factory methods instead of constructors) if the overloading is getting complicated. For other methods, renaming some cases or using a parameter object can help. This is when you have enough complexity that differentiating is difficult. A definite case is where you have to differentiate using the order of parameters not just number and type.

181
user46646

Can anybody tell what is the module/method used to get current time?

Answered By: Harley Holcombe ( 187)
>>> from datetime import datetime
>>> datetime.now()
datetime(2009, 1, 6, 15, 8, 24, 78915)

And just the time:

>>> datetime.time(datetime.now())
datetime.time(15, 8, 24, 78915)

See the documentation for more info.

I am a long-time Applescript user and new shell scripter who wants to learn a more general scripting language like Javascript or Python for performance reasons.

I am having trouble getting my head around concepts like object orientation, classes and instantiation.

If someone could point me to a pithy explanation of methods vs. functions it might help me get over the "hump". The explanations I found using google are just barely over my head.

Thanks.

Answered By: Andrew Edgecombe ( 163)

A function is a piece of code that is called by name. It can be passed data to operate on (ie. the parameters) and can optionally return data (the return value).

All data that is passed to a function is explicitly passed.

A method is a piece of code that is called by name that is associated with an object. In most respects it is identical to a function except for two key differences.

  1. It is implicitly passed the object for which it was called
  2. It is able to operate on data that is contained within the class (remembering that an object is an instance of a class - the class is the definition, the object is an instance of that data)

(this is a simplified explanation, ignoring issues of scope etc.)