Python staticmethod
1 @staticmethod 静态方法
when this method is called, we don't pass an instance of the class to it (as we normally do with methods).
This means you can put a function inside a class but you can't access the instance of that class (this is useful when your method does not use the instance).
当这个方法被调用时,我们不会将类的实例传递给它(就像我们通常用方法做的那样)。
这意味着你可以在一个类中放入一个函数,但是你不能访问该类的实例(当你的方法不使用实例时这很有用)
关于参数:该方法不强制要求传递参数,(如不需要表示自身对象的self和自身类的cls参数,就跟使用函数一样。)
如下声明一个静态方法:
class C(object):
@staticmethod
def f(arg1, arg2, ...):
...
以上实例声明了静态方法 f,类可以不用实例化就可以调用该方法 C.f(),当然也可以实例化后调用 C().f()。
函数语法:staticmethod(function)
例如:
#!/usr/bin/python
# -*- coding: UTF-8 -*- class C(object):
@staticmethod
def f():
print('runoob'); C.f(); # 静态方法无需实例化
cobj = C()
cobj.f() # 也可以实例化后调用
又如:
# 类中
@staticmethod
def is_date_valid(date_as_string):
day, month, year = map(int, date_as_string.split('-'))
return day <= 31 and month <= 12 and year <= 3999 # usage:
is_date = Date.is_date_valid('11-09-2012')
这里结果(is_date)是True/False
2 @classmethod 类方法
when this method is called, we pass the class as the first argument instead of the instance of that class (as we normally do with methods).
This means you can use the class and its properties inside that method rather than a particular instance.
当调用此方法时,我们将该类作为第一个参数传递,而不是该类的实例(正如我们通常对方法所做的那样)。
这意味着您可以在该方法内使用该类及其属性,而不能使用特定的实例。
关于参数:该方法强制要求传递一个必须参数, 不需要self参数,但第一个参数需要是表示自身类的cls参数。
如:
#!/usr/bin/python
# -*- coding: UTF-8 -*- class A(object):
bar = 1
def func1(self):
print ('foo')
@classmethod
def func2(cls):
print ('func2')
print (cls.bar)
cls().func1() # 调用 foo 方法 A.func2() # 不需要实例化
例如:
# 类中
@classmethod
def from_string(cls, date_as_string):
day, month, year = map(int, date_as_string.split('-'))
date1 = cls(day, month, year)
return date1 date2 = Date.from_string('11-09-2012')
这里结果(date2)是一个Date的实例。
他有如下好处:
- We've implemented date string parsing in one place and it's reusable now.
- Encapsulation works fine here (if you think that you could implement string parsing as a single function elsewhere, this solution fits OOP paradigm far better).
cls
is an object that holds class itself, not an instance of the class. It's pretty cool because if we inherit ourDate
class, all children will havefrom_string
defined also.
简单来说就是,可以有无限的from_string方法。
3 实例方法
4 最后:
使用@classmethod或@staticmethod都可以类名.方法名()调用函数
前者必须要一个类参数,后者可以不必须要参数
class Date(object): def __init__(self, day=0, month=0, year=0):
self.day = day
self.month = month
self.year = year @classmethod
def from_string(cls, date_as_string):
day, month, year = map(int, date_as_string.split('-'))
date1 = cls(day, month, year)
return date1 @staticmethod
def is_date_valid(date_as_string):
day, month, year = map(int, date_as_string.split('-'))
return day <= 31 and month <= 12 and year <= 3999 date2 = Date.from_string('11-09-2012')
is_date = Date.is_date_valid('11-09-2012')
Python staticmethod的更多相关文章
- Python staticmethod() 函数
Python staticmethod() 函数 Python 内置函数 python staticmethod 返回函数的静态方法. 该方法不强制要求传递参数,如下声明一个静态方法: class ...
- python staticmethod classmethod
http://www.cnblogs.com/chenzehe/archive/2010/09/01/1814639.html classmethod:类方法staticmethod:静态方法 在py ...
- Python staticmethod classmethod 普通方法 类变量 实例变量 cls self 概念与区别
类变量 1.需要在一个类的各个对象间交互,即需要一个数据对象为整个类而非某个对象服务. 2.同时又力求不破坏类的封装性,即要求此成员隐藏在类的内部,对外不可见. 3.有独立的存储区,属于整个类. ...
- python staticmethod,classmethod方法的使用和区别以及property装饰器的作用
class Kls(object): def __init__(self, data): self.data = data def printd(self): print(self.data) @st ...
- python @staticmethod和@classmethod
Python其实有3个方法,即 静态方法 (staticmethod), 类方法 (classmethod)和 实例方法. 如下: def foo(x): print "executing ...
- python staticmethod和classmethod(转载)
staticmethod, classmethod 分别被称为静态方法和类方法. staticmethod 基本上和一个全局函数差不多,只不过可以通过类或类的实例对象(python里只说对象总是容易产 ...
- python staticmethod&classmethod
python中的这两种方法都通过修饰器来完成 静态方法: 不需要传递类对象或者类的实例 可以通过类的实例.方法名a().foo()或者类名.方法a.foo()名来访问 当子类继承父类时,且实例化子类时 ...
- python staticmethod and classmethod方法
静态方法无绑定,和普通函数使用方法一样,只是需要通过类或者实例来调用.没有隐性参数. 实例方法针对的是实例,类方法针对的是类,他们都可以继承和重新定义,而静态方法则不能继承,可以认为是全局函数. #h ...
- python @staticmethod和@classmethod的作用
一般来说,要使用某个类的方法,需要先实例化一个对象再调用方法. 而使用@staticmethod或@classmethod,就可以不需要实例化,直接类名.方法名()来调用. 这有利于组织代码,把某些应 ...
随机推荐
- django实现密码非加密的注册(数据对象插入)
数据模型 from django.db import models class userinfo(models.Model): username = models.CharField(max_leng ...
- 数据库之MySQL(三)
视图 视图是一个虚拟表(非真实存在),其本质是[根据SQL语句获取动态的数据集,并为其命名],用户使用时只需使用[名称]即可获取结果集,并可以将其当作表来使用. 临时表搜索 SELECT *FRO ...
- create ‘/.git/index.lock’: File exists.
Git – fatal: Unable to create ‘/.git/index.lock’: File exists. fatal: Unable to create ‘/path/my_pro ...
- 剑指offer 面试27题
面试27题: 题目:二叉树的镜像 题:操作给定的二叉树,将其变换为源二叉树的镜像. 输入描述: 二叉树的镜像定义:源二叉树 8 / \ 6 10 / \ / \ 5 7 9 11 镜像二叉树 8 / ...
- 【转】Python max内置函数详细介绍
#max() array1 = range(10) array2 = range(0, 20, 3) print('max(array1)=', max(array1)) print('max(arr ...
- MySQL数据库(9)_MySQL数据库常用操作命令
注:刚安装好的MySql包含一个含空密码的root帐户和一个匿名帐户,这是很大的安全隐患,对于一些重要的应用我们应将安全性尽可能提高,在这里应把匿名帐户删除. root帐户设置密码,可用如下命令进行: ...
- 03 Spring框架 bean的属性以及bean前处理和bean后处理
整理了一下之前学习spring框架时候的一点笔记.如有错误欢迎指正,不喜勿喷. 上一节我们给出了三个小demo,具体的流程是这样的: 1.首先在aplicationContext.xml中添加< ...
- C# TreeView,递归循环数据加载到treeView1中
TblAreaBLL bll = new TblAreaBLL(); private void button1_Click(object sender, EventArgs e) { LoadData ...
- Ajax在jQuery中的应用---加载异步数据
Ajax是Asynchronous JavaScript and XML的缩写,其核心是通过XMLHttpRequest对象,以一种异步的方式,向服务器发送数据请求,并通过该对象接收请求返回的数据,从 ...
- 跨平台移动开发 Xuijs超轻量级的框架Style CSS属性用法
PhoneGap里面推荐使用的超轻量级的框架 Style CSS属性用法 设置css属性:setstyle 通过ID设置css属性 x$('#top1').setStyle('color', '#DB ...