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
4

3 に答える 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?

于 2012-07-02T05:03:08.047 に答える
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
于 2012-07-02T06:57:37.770 に答える
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.

于 2012-07-02T06:14:44.467 に答える