python @ property classmethod staticmethod
2016-04-19 16:59
609 查看
property
class property([fget[, fset[, fdel[, doc]]]])Return a property attribute for new-style classes (classes that derive from object). fget is a function for getting an attribute value. fset is a function for setting an attribute value. fdel is a function for deleting an attribute value. And doc creates a docstring for the attribute. A typical use is to define a managed attribute x:
class C(object): def __init__(self): self._x = None def getx(self): return self._x def setx(self, value): self._x = value def delx(self): del self._x x = property(getx, setx, delx, "I'm the 'x' property.")
If c is an instance of C, c.x will invoke the getter, c.x = value will invoke the setter and del c.x the deleter. If given, doc will be the docstring of the property attribute. Otherwise, the property will copy fget‘s docstring (if it exists). This makes it possible to create read-only properties easily using property() as a decorator:
class Parrot(object): def __init__(self): self._voltage = 100000 @property def voltage(self): """Get the current voltage.""" return self._voltage
The @property decorator turns the voltage() method into a “getter” for a read-only attribute with the same name, and it sets the docstring for voltage to “Get the current voltage.” A property object has getter, setter, and deleter methods usable as decorators that create a copy of the property with the corresponding accessor function set to the decorated function. This is best explained with an example:
class C(object): def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x
This code is exactly equivalent to the first example. Be sure to give the additional functions the same name as the original property (x in this case.) The returned property object also has the attributes fget, fset, and fdel corresponding to the constructor arguments.
一般来说,要使用某个类的方法,需要先实例化一个对象再调用方法。而使用@staticmethod或@classmethod,就可以不需要实例化,直接类名.方法名()来调用。这有利于组织代码,把某些应该属于某个类的函数给放到那个类里去,同时有利于命名空间的整洁。
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- ''' Created on 2016/05/04 File Name:python_test.py author: LindenTao Description : classmethod staticmethod ''' class A(object): # 实例方法 def foo(self,x): print "executing foo(%s,%s)"%(self,x) # 类方法:隐藏传递给第一个参数的是对象实体的类(class A)而不是self @classmethod def class_foo(cls,x): print "executing class_foo(%s,%s)"%(cls,x) # 静态方法:不管传递给第一个参数的是self(对象实体)还是cls(类).它们的表现都一样 @staticmethod def static_foo(x): print "executing static_foo(%s)"%x a=A() a.foo(1) # executing foo(<__main__.A object at 0x000000000223C400>,1) A.class_foo(1) # executing class_foo(<class '__main__.A'>,1) A.static_foo(1) # executing static_foo(1)
classmethod
classmethod(function)Return a class method for function. A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom: class C(object): @classmethod def f(cls, arg1, arg2, ...): ... The @classmethod 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. If a class method is called for a derived class, the derived class object is passed as the implied first argument. Class methods are different than C++ or Java static methods. If you want those, see staticmethod() in this section.
staticmethod
staticmethod(function)Return a static method for function. A static method does not receive an implicit first argument. To declare a static method, use this idiom:
class C(object): @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++. Also see classmethod() for a variant that is useful for creating alternate class constructors.
参考链接:
https://docs.python.org/2/library/functions.html相关文章推荐
- 机器学习系列(9)_机器学习算法一览(附Python和R代码)
- python 爬虫 beautifulsoup example 例子
- 机器学习算法笔记系列之深入理解主成分分析PCA-Python实现篇
- Mac 安装 Scrapy
- wxPython 图形界面程序时 多个显示器问题。
- Python中关于封装,继承,多态的表述
- python3时间处理
- Python 解析配置模块之ConfigParser详解
- Python 编辑器 tips
- python 字典get方法
- Python学习(2)基本语法
- python学习笔记(pict+requests+xml)
- 【python小练】0017-将xls文件内容写入xml文件中
- Python学习笔记(九)
- python学习
- python 鸭子类型
- Python字符串的方法及注释
- python 安装lxml失败
- Python webdriver 常见异常及描述
- python itertools模块