GVKun编程网logo

Python:从字符串名称调用函数(python通过字符串调用函数)

11

本文的目的是介绍Python:从字符串名称调用函数的详细情况,特别关注python通过字符串调用函数的相关信息。我们将通过专业的研究、有关数据的分析等多种方式,为您呈现一个全面的了解Python:从字

本文的目的是介绍Python:从字符串名称调用函数的详细情况,特别关注python通过字符串调用函数的相关信息。我们将通过专业的研究、有关数据的分析等多种方式,为您呈现一个全面的了解Python:从字符串名称调用函数的机会,同时也不会遗漏关于C#通过字符串名称来调用对应字符串名称的方法、PHP使用字符串名称调用类的方法是什么、python – Pandas:从字符串中删除编码、python – 根据列表中的字符串调用函数的知识。

本文目录一览:

Python:从字符串名称调用函数(python通过字符串调用函数)

Python:从字符串名称调用函数(python通过字符串调用函数)

我有一个str对象,例如:menu = ''install''。我想从此字符串运行安装方法。例如,当我打电话menu(some,arguments)时它将呼叫install(some, arguments)。有什么办法吗?

答案1

小编典典

如果在课程中,则可以使用getattr:

class MyClass(object):    def install(self):          print "In install"method_name = ''install'' # set by the command line optionsmy_cls = MyClass()method = Nonetry:    method = getattr(my_cls, method_name)except AttributeError:    raise NotImplementedError("Class `{}` does not implement `{}`".format(my_cls.__class__.__name__, method_name))method()

或者它是一个函数:

def install():       print "In install"method_name = ''install'' # set by the command line optionspossibles = globals().copy()possibles.update(locals())method = possibles.get(method_name)if not method:     raise NotImplementedError("Method %s not implemented" % method_name)method()

C#通过字符串名称来调用对应字符串名称的方法

C#通过字符串名称来调用对应字符串名称的方法

前段时间在一个项目中,在一个地方要将函数所在类中的方法都调用一遍,但是否调用要通过配置文件中的内容决定。所以为了减少代码量,在网上查了相关信息,终于成功的将其应用到了项目中,我在这里将我做的一个简单例子提供给大家,便于大家方便下载和理解。

主要用到了反射的一个特性,主要代码如下:

object[] _params = new object[kvp.Value.Length]; 
for (int i = 0; i <= _params.Length - 1; i++)
{
_params[i] = kvp.Value[i]; 
}

Type t = typeof(ListOfWay); 
MethodInfo mi = t.GetMethod(kvp.Key.ToString()); 
object objinstance = Activator.CreateInstance(t); 
int result = (int)mi.Invoke(objinstance, _params);

基本步骤就是:

1、将要调用的方法的参数全部依次放入一个object数组中;

2、用反射一个特性,获得方法所在类的类型;

3、根据对象和方法参数去调用这个方法。

 详细代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Reflection;

using TestWay;

namespace 加载xml及调用字符串名的函数
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, string[]> dict = new Dictionary<string, string[]>();
            string path = @"InputParam.xml";

            ReadXml(path, dict);

            foreach (KeyValuePair<string, string[]> kvp in dict)
            {

                #region 根据字符串去调用与字符串相同名称的方法
                object[] _params = new object[kvp.Value.Length];  //根据键值对中值的多少声明一个同样大小的字符串数组
                for (int i = 0; i <= _params.Length - 1; i++)
                {
                    _params[i] = kvp.Value[i];       //将键值对中的值写入数组中
                }

                Type t = typeof(ListOfWay);           //获得方法所在的类的类型
                MethodInfo mi = t.GetMethod(kvp.Key.ToString());       //根据字符串名称获得对应的方法
                object objinstance = Activator.CreateInstance(t);      //创建一个方法所在的类的一个对象
                int result = (int)mi.Invoke(objinstance, _params);     //根据对象和方法参数去执行方法
                #endregion

                Console.WriteLine(result);
            }

            Console.ReadLine();
        }

        #region Way2
        /// <summary>
        /// 读取XML文档
        /// </summary>
        /// <param name="path">xml路径(含名称)</param>
        /// <param name="dict">xml中参数字典</param>

        public static void ReadXml(string path, Dictionary<string, string[]> dict)
        {
            XmlDocument xml = new XmlDocument();
            xml.Load(path);
            XmlElement xmlRoot = xml.DocumentElement;      //根节点
            XmlNodeList xmllist = xmlRoot.ChildNodes;      //根节点下所有子节点(一般是二级节点)
            foreach (XmlNode item in xmllist)
            {
                XmlNodeList inxmllist = item.ChildNodes;   //每个子节点下的所有子节点(一般是三级节点,也基本是最内层节点)
                string[] param = new string[inxmllist.Count];
                for (int i = 0; i <= inxmllist.Count - 1; i++)
                {
                    param[i] = inxmllist[i].InnerText;     //将每个子节点的值放入数组
                }
                dict.Add(item.Name, param);
            }
        }
        #endregion

    }
}
View Code

用于测试的方法所在的类的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestWay
{
    public class ListOfWay
    {
        public int Add(string a, string b)
        {
            return Convert.ToInt32(a) + Convert.ToInt32(b);
        }
        public int Sub(string a, string b)
        {
            return Convert.ToInt32(a) - Convert.ToInt32(b);
        }
        public int Mul(string a, string b)
        {
            return Convert.ToInt32(a) * Convert.ToInt32(b);
        }
        public int Div(string a, string b)
        {
            return Convert.ToInt32(a) / Convert.ToInt32(b);
        }

    }
}
View Code

 

PHP使用字符串名称调用类的方法是什么

PHP使用字符串名称调用类的方法是什么

php使用字符串名称调用类的方法:1、使用【call_user_func】方法,代码为【call_user_func(array($game, ''play''), 1)】;2、使用play方法,代码为【$game->{''play''}(2)】。

PHP使用字符串名称调用类的方法是什么

本教程操作环境:windows7系统、PHP5.6版,DELL G3电脑,该方法适用于所有品牌电脑。

PHP使用字符串名称调用类的方法:

可以使用call_user_func方法和Play方法

具体代码如下显示:

立即学习“PHP免费学习笔记(深入)”;

<?php
class Game {
    function Play($id) {
        echo "Playing game $id\n";
    }
}
$game = new Game();
//方法1,使用call_user_func
call_user_func(array($game, &#39;Play&#39;), 1);
//方法2
$game->{&#39;Play&#39;}(2);
//或者
$method = &#39;Play&#39;;
$game->$method(3);
登录后复制

相关视频推荐:PHP编程从入门到精通

以上就是PHP使用字符串名称调用类的方法是什么的详细内容,更多请关注php中文网其它相关文章!

python – Pandas:从字符串中删除编码

python – Pandas:从字符串中删除编码

我有以下数据框:

str_value
0 Mock%20the%20Week
1 law
2 euro%202016

有许多这样的特殊字符,如%,%20等.如何将它们全部删除.我尝试了以下但数据框很大,我不确定有多少这样的不同字符.

dfSearch['str_value'] = dfSearch['str_value'].str.replace('%2520',' ')

dfSearch['str_value'] = dfSearch['str_value'].str.replace('%20',' ')

解决方法

您可以使用urllib库并使用系列的 map方法应用它.
示例 –

In [23]: import urllib

In [24]: dfSearch["str_value"].map(lambda x:urllib.unquote(x).decode('utf8'))
Out[24]:
0    Mock the Week
1              law
2        euro 2016

python – 根据列表中的字符串调用函数

python – 根据列表中的字符串调用函数

Terms: 
talib: Technical Analysis Library (stock market indicators,charts etc)
CDL: Candle or Candlestick

简短版本:我想基于字符串’some_function’运行my_lib.some_function()

在quantopian.com上,为了简洁起见,我想在循环中调用以CDL开头的所有60个talib函数,如talib.CDL2CROWS().首先将函数名称作为字符串,然后通过与字符串匹配的名称运行函数.

那些CDL函数都采用相同的输入,一段时间内的开放,高,低和收盘价格列表,这里的测试只使用长度为1的列表来简化.

import talib,re
import numpy as np

# Make a list of talib's function names that start with 'CDL'
cdls = re.findall('(CDL\w*)',' '.join(dir(talib)))
# cdls[:3],the first three like ['CDL2CROWS','CDL3BLACKCROWS','CDL3INSIDE']

for cdl in cdls:
    codeobj = compile(cdl + '(np.array([3]),np.array([4]),np.array([5]),np.array([6]))','talib','exec')
    exec(codeobj)
    break
# Output:  NameError: name 'CDL2CROWS' is not defined

尝试第二个:

import talib,re
import numpy as np

cdls = re.findall('(CDL\w*)',' '.join(dir(talib)))

for cdl in cdls:
    codeobj = compile('talib.' + cdl + '(np.array([3]),'','exec')
    exec(codeobj)
    break
# Output:  AssertionError: open is not double

我没有在网上找到这个错误.

相关的,我在那里问的问题:https://www.quantopian.com/posts/talib-indicators(111次观看,还没有回复)

对于任何对烛台感兴趣的人:http://thepatternsite.com/TwoCrows.html

更新

在Anzel的聊天帮助之后,这可能有用,可能浮动在列表中是关键.

import talib,re
import numpy as np
cdls = re.findall('(CDL\w*)',' '.join(dir(talib)))
# O,H,L,C = Open,High,Low,Close
O = [ 167.07,170.8,178.9,184.48,179.1401,183.56,186.7,187.52,189.0,193.96 ]
H = [ 167.45,180.47,185.83,185.48,184.96,186.3,189.68,191.28,194.5,194.23 ]
L = [ 164.2,169.08,178.56,177.11,177.65,180.5,185.611,186.43,188.0,188.37 ]
C = [ 166.26,177.8701,183.4,181.039,182.43,185.3,188.61,190.86,193.39,192.99 ]
for cdl in cdls: # the string that becomes the function name
    toExec = getattr(talib,cdl)
    out    = toExec(np.array(O),np.array(H),np.array(L),np.array(C))
    print str(out) + ' ' + cdl

选择如何为字符串转换函数添加参数:

toExec = getattr(talib,cdl)(args)
toExec()

要么

toExec = getattr(talib,cdl)
toExec(args)

解决方法

如果你想根据字符串’some_function’运行my_lib.some_function(),请使用getattr,如下所示:

some_function = 'your_string'
toExec = getattr(my_lib,some_function)

# to call the function
toExec()

# an example using math
>>> some_function = 'sin'
>>> toExec = getattr(math,some_function)

>>> toExec
<function math.sin>
>>> toExec(90)
0.8939966636005579

更新您的代码以便运行

for cdl in cdls:
    toExec = getattr(talib,cdl)

# turns out you need to pass narray as the params
toExec(np.narray(yourlist),np.narray(yourlist),np.narray(yourlist))

我还建议您需要查看您的列表,因为它是当前的1维,而您需要n维数组.

今天关于Python:从字符串名称调用函数python通过字符串调用函数的讲解已经结束,谢谢您的阅读,如果想了解更多关于C#通过字符串名称来调用对应字符串名称的方法、PHP使用字符串名称调用类的方法是什么、python – Pandas:从字符串中删除编码、python – 根据列表中的字符串调用函数的相关知识,请在本站搜索。

本文标签: