GVKun编程网logo

在python中动态声明/创建列表(python如何动态创建一个类)

29

本篇文章给大家谈谈在python中动态声明/创建列表,以及python如何动态创建一个类的知识点,同时本文还将给你拓展python中动态创建类、Python中动态创建类实例的方法、python中动态变

本篇文章给大家谈谈在python中动态声明/创建列表,以及python如何动态创建一个类的知识点,同时本文还将给你拓展python中动态创建类、Python中动态创建类实例的方法、python中动态变量创建、Python中如何使用list()函数创建列表等相关知识,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

在python中动态声明/创建列表(python如何动态创建一个类)

在python中动态声明/创建列表(python如何动态创建一个类)

我是python的初学者,并且满足在python脚本中动态声明/创建一些列表的要求。我需要在输入4时创建4个列表对象,例如depth_1,depth_2,depth_3,depth_4。

for (i = 1; i <= depth; i++){    ArrayList depth_i = new ArrayList();  //or as depth_i=[] in python}

以便它可以动态创建列表。您能为我提供解决方案吗?

感谢你在期待

答案1

小编典典

您可以使用globals()或进行所需的操作locals()

>>> g = globals()>>> for i in range(1, 5):...     g[''depth_{0}''.format(i)] = []... >>> depth_1[]>>> depth_2[]>>> depth_3[]>>> depth_4[]>>> depth_5Traceback (most recent call last):  File "<stdin>", line 1, in <module>NameError: name ''depth_5'' is not defined

为什么不使用清单清单?

>>> depths = [[] for i in range(4)]>>> depths[[], [], [], []]

python中动态创建类

python中动态创建类

class Foo(Bar):
    pass 

Foo中有__metaclass__这个属性吗?如果是,Python会在内存中通过__metaclass__创建一个名字为Foo的类对象(我说的是类对象,请紧跟我的思路)。如果Python没有找到__metaclass__,它会继续在Bar(父类)中寻找__metaclass__属性,并尝试做和前面同样的操作。如果Python在任何父类中都找不到__metaclass__,它就会在模块层次中去寻找__metaclass__,并尝试做同样的操作。如果还是找不到__metaclass__,Python就会用内置的type来创建这个类对象。

类也是对象,在Python中,我们可以动态的创建类 1、在函数内部,需要类时动态创建 2、使用type内建函数 3、使用一个魔法方法 metaclass

(一)

函数内部,在分支语句中创建类函数使用

def stu(name):
    if name == ''foo'': class Foo: print(''我是Foo...%s''%name) else: class XFoo: print(''我是XFoo...我被错误的创建了%s''%name) stu(''foo'') stu(123) 

以上就是用于检验引用函数时传入的参数是否合理

(二)

type内建函数

#创建无属性 无继承的类
Foo = type(''Foo'',(),{}) print(Foo) #创建有属性 无继承类 Foo = type(''Foo'',(),{''name'':''zhu''}) print(Foo.name) #创建有属性,有继承类 class Foo: name = ''zhu'' FooChild = type(''FooChild'',(Foo,),{''age'':19}) print(FooChild.name,FooChild.age) #创建带方法的类 def select(self): print(self.name) class Foo: name = ''zhu'' FooChild = type(''FooChild'',(Foo,),{''age'':19,''select'':select}) print(FooChild.name,FooChild.age,FooChild.select) fooChild = FooChild() fooChild.select() 

type()参数有三个,第一个是新建的类名,第二个是继承的父类,是一个元组,第三个是类具有的属性和方法,是一个字典,键是属性名或者方法名

(三)

使用魔法方法创建类 metaclass

def upper_attr(future_class_name, future_class_parents, future_class_attr):
    # 遍历属性字典,把不是__开头的属性名字变为大写 newAttr = {} for name, value in future_class_attr.items(): if not name.startswith("__"): newAttr[name.upper()] = value # 调用type来创建一个类 return type(future_class_name, future_class_parents, newAttr) class Foo(object, metaclass=upper_attr): bar = ''bip'' print(hasattr(Foo, ''bar'')) print(hasattr(Foo, ''BAR'')) 

__mataclass__是为了创建元类而存在,如果类的tree中有,就会调用此方法,如果没有就会使用type方法创建

Python中动态创建类实例的方法

Python中动态创建类实例的方法

简介

在Java中我们可以通过反射来根据类名创建类实例,那么在Python我们怎么实现类似功能呢?

其实在Python有一个builtin函数import,我们可以使用这个函数来在运行时动态加载一些模块。如下:

def createInstance(module_name,class_name,*args,**kwargs):
  module_Meta = __import__(module_name,globals(),locals(),[class_name])
  class_Meta = getattr(module_Meta,class_name)
  obj = class_Meta(*args,**kwargs)
  return obj

例子

首先我们建一个目录 my_modules,其中包括三个文件

* init.py: 模块文件
* my_module.py: 测试用的模块
* my_another_module: 另一个测试用的模块

my_module.py

from my_modules.my_another_module import *
class MyObject(object):
  def test(self):
    print 'MyObject.test'
    MyObject1().test()
    MyObject2().test()
    MyAnotherObject().test()
class MyObject1(object):
  def test(self):
    print 'MyObject1.test'
class MyObject2(object):
  def test(self):
    print 'MyObject2.test'

my_another_module.py

class MyAnotherObject(object):
  def test(self):
    print 'MyAnotherObject.test'

test.py

def createInstance(module_name,**kwargs)
  return obj
obj = createInstance("my_modules.my_module","MyObject")
obj.test()
MyObject.test
MyObject1.test
MyObject2.test
MyAnotherObject.test

pyinstaller集成

对于使用pyinstaller打包的应用程序,如果使用上面的代码,运行打包后的程序会出现下面的错误

Traceback (most recent call last):
 File "test.py",line 12,in <module>
  obj = createInstance("my_modules.my_module","MyObject")
 File "test.py",line 7,in createInstance
  module_Meta = __import__(module_name,[class_name])
ImportError: No module named my_modules.my_module
Failed to execute script test

这里错误的原因是 pyinstaller 在打包分析类的时候没有分析到 my_modules 下面的模块,所以运行报错。

解决办法一:

在 test.py 中把 my_modules 下的模块手动 import,见下面代码中的第一行。这种方法最简单,但是显然不太好。

import my_modules.my_module
def createInstance(module_name,"MyObject")
obj.test()

解决办法二:

在使用 pyinstaller 打包的时候,指定 “Chidden-import”,如下

pyinstaller -D --hidden-import my_modules.my_module test.py

解决办法三:

动态修改 python 运行时path,见下面代码中的前两行,其中path我们可以通过环境变量或者参数传递进来。显然这种方法要比前两种方法灵活的多。

import sys
sys.path.append(...)
def createInstance(module_name,"MyObject")
obj.test()

以上所述是小编给大家介绍的Python中动态创建类实例的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对编程小技巧网站的支持!

python中动态变量创建

python中动态变量创建

1、locals()返回一个字典包含当前作用域的局部变量。

2、globals()返回一个字典包含当前的作用域的全局变量。

3、vars()不带参数时,相当于locals(),带参数时相当于object.__dict__。

4、类可以用setattr(self,k,v)。

5、类self.__dict__.update(kwds)

Python中如何使用list()函数创建列表

Python中如何使用list()函数创建列表

python中如何使用list()函数创建列表

Python中如何使用list()函数创建列表

Python是一种功能强大的编程语言,其中一个非常实用的功能是列表。列表是一种可以存储多个值的数据结构,可以是不同类型的值。在Python中,我们可以使用list()函数来创建一个列表。

list()函数是一个内置函数,它可以将其他可迭代对象转换为一个列表。可迭代对象可以是字符串、元组、集合、字典等。让我们来看几个示例来了解如何使用list()函数创建列表。

首先,我们可以将一个字符串转换为一个包含每个字符的列表。例如,我们有一个字符串"Hello World",我们想要将其转换为一个列表:

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

string = "Hello World"
list_string = list(string)
print(list_string)
登录后复制

输出结果为:[''H'', ''e'', ''l'', ''l'', ''o'', '' '', ''W'', ''o'', ''r'', ''l'', ''d'']

我们可以看到,字符串中的每个字符都被转换为了一个列表中的元素。

接下来,我们可以将一个元组转换为一个列表。元组是不可变的序列,与列表类似,但它们的元素不能被改变。例如,我们有一个元组(1, 2, 3, 4, 5),我们可以使用list()函数将其转换为一个列表:

tuple_nums = (1, 2, 3, 4, 5)
list_nums = list(tuple_nums)
print(list_nums)
登录后复制

输出结果为:[1, 2, 3, 4, 5]

我们还可以将一个集合转换为一个列表。集合是一个无序的不重复元素的集合。例如,我们有一个集合{1, 2, 3, 4, 5},我们可以使用list()函数将其转换为一个列表:

set_nums = {1, 2, 3, 4, 5}
list_nums = list(set_nums)
print(list_nums)
登录后复制

输出结果为:[1, 2, 3, 4, 5]

最后,我们可以将一个字典的键或值转换为一个列表。字典是一种用键值对存储数据的数据结构。例如,我们有一个字典{"name": "John", "age": 25, "city": "New York"},我们可以使用list()函数将其键转换为一个列表:

dict_info = {"name": "John", "age": 25, "city": "New York"}
list_keys = list(dict_info.keys())
print(list_keys)
登录后复制

输出结果为:[''name'', ''age'', ''city'']

同样地,我们可以使用list()函数将字典的值转换为一个列表:

list_values = list(dict_info.values())
print(list_values)
登录后复制

输出结果为:[''John'', 25, ''New York'']

除了以上示例外,我们还可以使用list()函数将其他可迭代对象如文件对象、生成器、区间对象等转换为一个列表。

总结一下,Python中的list()函数是一个非常方便的函数,可以将其他可迭代对象转换为一个列表。通过这个函数,我们可以快速简便地创建列表并进行后续的操作和处理。

以上是关于如何使用list()函数创建列表的介绍,希望对你在Python中使用列表有所帮助。祝你编程愉快!

以上就是Python中如何使用list()函数创建列表的详细内容,更多请关注php中文网其它相关文章!

关于在python中动态声明/创建列表python如何动态创建一个类的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于python中动态创建类、Python中动态创建类实例的方法、python中动态变量创建、Python中如何使用list()函数创建列表等相关内容,可以在本站寻找。

本文标签: