+ 1

Please explain any classmethod , staticmethod , properties to me ,I'm unable to understand with given examples

1st Apr 2017, 8:21 PM
Purvang Upadhyay
Purvang Upadhyay - avatar
1 Antwort
+ 7
classmethod and staticmethod: In Python, when you want to call the method of a class you just defined, you first have to make an instance of the class and then call the method from the object: # defining the class class A: def my_method(self): print('called my_method') # instanciating it obj = A() # calling the method obj.my_method() But when you define a method as a staticmethod or as a classmethod you don't need to create an instance of the class to call the method: # defining the class class A: @classmethod def my_classmethod(cls): print('called my_classmethod') @staticmethod def my_staticmethod(): print('called my_staticmethod') # calling the methods A.my_classmethod() A.my_staticmethod() The example also shows the difference of class and static methods. It is how they are defined: -- classmethods have at leats one parameter (a reference to the class); -- staticmethods can have no parameter; properties: Properties are used to control the access to the class attributes. We can control if someone tries to read it or change it: class A: def __init__(self): _secret = 'very secret data' # this is the attribute I want to control access to @property def secret(self): # this is what will be called when someone tries to read the attribute password = input('what is the password: ') if password == 'correct password': return _secret else: print('you are not allowed access.') @secret.setter def secret(self, value): # this is what will be called when someone tries to change the value if value != 'eggs': _secret = value more information here: https://docs.python.org/2/library/functions.html
2nd Apr 2017, 3:06 AM
Ulisses Cruz
Ulisses Cruz - avatar