设万维读者为首页 万维读者网 -- 全球华人的精神家园 广告服务 联系我们 关于万维
 
首  页 新  闻 视  频 博  客 论  坛 分类广告 购  物
搜索>> 发表日志 控制面板 个人相册 给我留言
帮助 退出
我的薄客  
自己的空间, 不薄没客  
https://blog.creaders.net/u/15920/ > 复制 > 收藏本页
网络日志正文
Python Tips 2018-11-26 08:19:13

Enumerate is a built-in function of Python, which allows us to loop over something and have an automatic counter. 


for counter, value in enumerate(some_list):
    print(counter, value)


my_list = ['apple', 'banana', 'grapes', 'pear']for c, value in enumerate(my_list, 1):
    print(c, value)# Output:# 1 apple# 2 banana# 3 grapes# 4 pear


my_list = ['apple', 'banana', 'grapes', 'pear']
counter_list = list(enumerate(my_list, 1))
print(counter_list)
# Output: [(1, 'apple'), (2, 'banana'), (3, 'grapes'), (4, 'pear')]


 *args and **kwargs


*args and **kwargs are mostly used in function definitions. *args and **kwargs allow you to pass a variable number of arguments to a function. 


*args is used to send a non-keyworded variable length argument list to the function. 


def test_var_args(f_arg, *argv):
    print("first normal arg:", f_arg)
    for arg in argv:
        print("another arg through *argv:", arg)
        
test_var_args('yasoob', 'python', 'eggs', 'test')


first normal arg: yasoob
another arg through *argv: python
another arg through *argv: eggs
another arg through *argv: test


**kwargs allows you to pass keyworded variable length of arguments to a function. You should use **kwargs if you want to handle named arguments in a function. 


def greet_me(**kwargs):
    for key, value in kwargs.items():
        print("{0} = {1}".format(key, value))
        
>>> greet_me(name="yasoob")
name = yasoob


So here we will see how to call a function using *args and **kwargs. Just consider that you have this little function:

def test_args_kwargs(arg1, arg2, arg3):
    print("arg1:", arg1)
    print("arg2:", arg2)
    print("arg3:", arg3)

Now you can use *args or **kwargs to pass arguments to this little function. Here’s how to do it:

# first with *args
>>> args = ("two", 3, 5)
>>> test_args_kwargs(*args)
arg1: two
arg2: 3
arg3: 5

# now with **kwargs:
>>> kwargs = {"arg3": 3, "arg2": "two", "arg1": 5}
>>> test_args_kwargs(**kwargs)
arg1: 5
arg2: two
arg3: 3


Order of using *args **kwargs and formal args

So if you want to use all three of these in functions then the order is

some_func(fargs, *args, **kwargs)


The most common use case is when making function decorators. Moreover it can be used in monkey patching as well. Monkey patching means modifying some code at runtime. Consider that you have a class with a function called get_info which calls an API and returns the response data. If we want to test it we can replace the API call with some test data. For instance:

import someclass

def get_info(self, *args):
    return "Test data"
    
someclass.get_info = get_info


Object introspection

In computer programming, introspection is the ability to determine the type of an object at runtime. It is one of Python’s strengths. Everything in Python is an object and we can examine those objects. Python ships with a few built-in functions and modules to help us.

dir

It is one of the most important functions for introspection. It returns a list of attributes and methods belonging to an object. Here is an example:

my_list = [1, 2, 3]dir(my_list)# Output: ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',# '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',# '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__',# '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__',# '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__',# '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__',# '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop',# 'remove', 'reverse', 'sort']

Our introspection gave us the names of all the methods of a list. This can be handy when you are not able to recall a method name. If we run dir() without any argument then it returns all names in the current scope.

type and id

The type function returns the type of an object. For example:

print(type(''))# Output: print(type([]))# Output: print(type({}))# Output: print(type(dict))# Output: print(type(3))# Output:

id returns the unique ids of various objects. For instance:

name = "Yasoob"print(id(name))# Output: 139972439030304


inspect module

The inspect module also provides several useful functions to get information about live objects. For example you can check the members of an object by running:

import inspectprint(inspect.getmembers(str))# Output: [('__add__', <slot wrapper '__add__' of ... ...

There are a couple of other methods as well which help in introspection.


浏览(953) (3) 评论(0)
发表评论
我的名片
chinese_wolf
注册日期: 2018-11-02
访问总量: 10,889 次
点击查看我的个人资料
Calendar
最新发布
· 我们的天使
· Learned today
· Python Tips
分类目录
【深度学习,训练记录】
· 我们的天使
· Learned today
· Python Tips
存档目录
2020-07-16 - 2020-07-16
2018-11-26 - 2018-11-30
 
关于本站 | 广告服务 | 联系我们 | 招聘信息 | 网站导航 | 隐私保护
Copyright (C) 1998-2024. Creaders.NET. All Rights Reserved.