0

I some questions about some code I've been looking at. What does the @staticmethod and @property mean when it is written above a method definition in Python like the following?

@staticmethod 
def methodName(parameter):
    Class_Name.CONSTANT_VARIABLE = parameter

@property
def methodName(parameter):
    Class_Name.CONSTANT_VARIABLE = parameter
2
  • 7
    Docs? staticmethod , property Commented Jul 2, 2012 at 4:56
  • 2
    Check out link Commented Jul 2, 2012 at 5:10

3 Answers 3

2

The decorator syntax is shorthand for this pattern.

def methodName(parameter):
    Class_Name.CONSTANT_VARIABLE = parameter
methodName = some_decorator(methodName)

can be rearranged like this

@some_decorator
def methodName(parameter):
    Class_Name.CONSTANT_VARIABLE = parameter

One advantage is that it sits at the top of the function, so it is clear that it is a decorated function

Are you also asking what staticmethods and properties are?

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for the help but I guess I am also asking what staticmethods and properties are.
1

There is a sample code

class Class1(object):
    def __init__(self):
        self.__x = None

#       you can call this method without instance of a class like Class1.method1()
    @staticmethod
    def method1():
        return "Static method"

    def method2(self):
        return "Class method"

    @property
    def x(self):
        print "In getter"
        return self.__x

    @x.setter
    def x(self, value):
        print "In Setter"
        self.__x = value

Comments

0

A staticmethod is just a function that has been included in a class definition. Unlike regular methods, it will not have a self argument.

A property is a method that gets run upon attribute lookup. The principal purpose of a property to is support attribute lookup but actually run code as if a method call had been made.

3 Comments

Thank you very much Raymond. To clarify, is one of the reasons to use a staticmethod possibly to change a class variable when the staticmethod of the class is invoked? Also, what do you mean by "A property is a method that gets run upon attribute lookup?" I've only been learning how to program for the past 6 months and have never heard about this. Thanks for the help in advance!
Static methods are used for functionality that doesn't need access to either an instance or the class itself (that is why there is no self or class in the parameter list for a static method). Accordingly, static methods are not used to change class variables (they don't even know about the class they are in).
Then in what way would you actually use a static method? For example, could you use it to change a class CONSTANT? Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.