GVKun编程网logo

Python: callbacks and mix-in class

1

在本文中,我们将为您详细介绍Python:callbacksandmix-inclass的相关知识,此外,我们还会提供一些关于Callbacks,PromisesandAsync/Await、clas

在本文中,我们将为您详细介绍Python: callbacks and mix-in class的相关知识,此外,我们还会提供一些关于Callbacks, Promises and Async/Await、class.__mro__、class.mro()、class.__subclasses__()如何使用、css – ‘div .class’,’.class’和’.class div’之间的差异、css – “.class”和“.class,.class .class”之间的区别?的有用信息。

本文目录一览:

Python: callbacks and mix-in class

Python: callbacks and mix-in class

What''s the problem?

Assuming that you have some well written library which parses a file and invokes callbacks when some certain pattern''s encountered (For example, SAX).

The most common way to make use of its utility is to inherit from it, override the callbacks and do your own stuff.

Here''s a small piece of code demonstrating this method:

import re, sys
class Substantial:
    regexp_callback = re.compile(r''<([^<>]+)>'')
    def callback(self, name=None):
        print ''Substantial callback''
    def parse(self, string):
        m = self.regexp_callback.match(string)
        if m:
            self.callback(m.group(1))

class MyHandler(Substantial):
    def callback(self, name=None):
        print ''MyHandler callback''
        # we''re likely to have a long-long if-else statement here     
        # without mixin class

As the code comment states, WE ARE LIKELY TO HAVE A LONG IF-ELSE STATEMENT IN CALLBACKS.

Assuming the input file has contents like:

<callback1>

<hello>

<nice>

...

It''s probable that we''ve got to write code in callbacks like this:

if content-in-angle-brackets == ''callback1'': XXXX

elif content-in-angle-brackets == ''hello'': XXXX

.....

This is not scalable and difficult to maintain!

How do we solve this problem, i.e, avoid the long if-else statement to make the project more maintainable?

First Solution to Avoid Long If-Else problem

The first solution may be obvious. Most of us may code like this:

class MyHandler(Substantial):
    def callback(self, name=None):
        # we''re likely to have a long-long if-else statement here                                                                                                                                               
        # without mixin class                                                                                                                                                                                   
        if name.upper() == ''CALLBACK1'':
            self.doCALLBACK1()
        elif name.upper() == ''CALLBACK2'':
            self.doCALLBACK2()
        elif name.upper() == ''CALLBACK3'':
            self.doCALLBACK3()
    # actual callbacks                                                                                                                                                                                          
    def doCALLBACK1(self):
        print ''MyHandler: doCALLBACK1''
    def doCALLBACK2(self):
        print ''MyHandler: doCALLBACK2''
    def doCALLBACK3(self):
        print ''MyHandler: doCALLBACK3''

def parseFile(filename, handler):
    with open(filename, "r") as f:
        for line in f:
            handler.parse(line.strip())

Well, this is acceptable, but the long if-else problem''s still there. If We''re going to define 10 callbacks, we''re forced to write 10 if-elif statements. Isn''t there any better way? Say, we just write a small piece of code, and this code takes care of dispatching methods, and the only thing we should focus on is to write well-defined callbacks.

A Better Solution: mix-in class (used as a dispatcher and helper)

The solution is that by introducing a mix-in class, we delegate the dispatching task to the mix-in class and only focus on actual callback functions.

The code is like this.

class Mixin:
    def callback(self, name=None):
        if name:
            mname = ''do''+name.upper()
            method = getattr(self, mname, None)
            if callable(method):
                method()

class MyHandler2(Mixin, Substantial):
    # actual callbacks                                                                                                                                                                                          
    def doCALLBACK1(self):
        print ''MyHandler2: doCALLBACK1''
    def doCALLBACK2(self):
        print ''MyHandler2: doCALLBACK2''
    def doCALLBACK3(self):
        print ''MyHandler2: doCALLBACK3''

Demo

if __name__ == ''__main__'':
    if len(sys.argv) < 2:
        print ''argument error, please specify an input file''
    else:
        print ''=======Substantial================''
        parseFile(sys.argv[1], Substantial())
        print ''=======MyHandler(Directly inherit from Substantial==========''
        parseFile(sys.argv[1], MyHandler())
        print ''=======MyHandler2 (Inherit from Mixin and Substantial, Mixin as a dispather or helper) ==''
        parseFile(sys.argv[1], MyHandler2())


input file contents:

<hello>
world
{callBack1}
{callBack2}
<callBack1>
<callBack2>
hello
world
<callback3>
<mycallback>

Result

chenqi@chenqi-OptiPlex-760:~/mypro/python/xml-parser$ ./test.py input
=======Substantial================
Substantial callback
Substantial callback
Substantial callback
Substantial callback
Substantial callback
=======MyHandler(Directly inherit from Substantial==========
MyHandler: doCALLBACK1
MyHandler: doCALLBACK2
MyHandler: doCALLBACK3
=======MyHandler2 (Inherit from Mixin and Substantial, Mixin as a dispather or helper) ==
MyHandler2: doCALLBACK1
MyHandler2: doCALLBACK2
MyHandler2: doCALLBACK3
chenqi@chenqi-OptiPlex-760:~/mypro/python/xml-parser$

Callbacks, Promises and Async/Await

Callbacks, Promises and Async/Await

本文转自作者Sandeep Dinesh的文章:Callbacks, Promises and Async/Await

假设你有一个函数可以在一段随机的时间后打印一个字符串:

function printString(string){
  setTimeout(
    () => {
      console.log(string)
    }, 
    Math.floor(Math.random() * 100) + 1
  )
}

让我们尝试按顺序打印字母A,B,C:

function printAll(){
  printString("A")
  printString("B")
  printString("C")
}
printAll()

每次调用printAll时,您会注意到A,B和C以不同的随机顺序打印!

这是因为这些函数是异步的。每个函数按顺序执行,但每个函数都独立于它自己的setTimeout。在开始之前,他们不会等待最后一个功能完成。

这非常烦人,所以让我们用回调修复它。

Callbacks

回调是传递给另一个函数的函数。第一个函数完成后,它将运行第二个函数。

function printString(string, callback){
  setTimeout(
    () => {
      console.log(string)
      callback()
    }, 
    Math.floor(Math.random() * 100) + 1
  )
}

你可以看到,修改原始函数是非常容易的,可以使用回调。

再次,让我们尝试按顺序打印字母A,B,C:

function printAll(){
  printString("A", () => {
    printString("B", () => {
      printString("C", () => {})
    })
  })
}
printAll()

嗯,代码现在很丑陋,但至少它有效!每次调用printAll时,都会得到相同的结果。

回调的问题是它创建了一个名为“Callback Hell”的东西。基本上,你开始在函数内的函数内嵌套函数,并且开始变得非常难以阅读代码。

Promise

Promise尝试修复这个嵌套问题。让我们改变我们的功能来使用Promises

function printString(string){
  return new Promise((resolve, reject) => {
    setTimeout(
      () => {
       console.log(string)
       resolve()
      }, 
     Math.floor(Math.random() * 100) + 1
    )
  })
}

你可以看到它看起来仍然非常相似。您将整个函数包装在Promise中,而不是调用回调,而是调用resolve(如果出现错误则拒绝)。该函数返回此Promise对象。

再次,让我们尝试按顺序打印字母A,B,C:

function printAll(){
  printString("A")
  .then(() => {
    return printString("B")
  })
  .then(() => {
    return printString("C")
  })
}
printAll()

这被称为承诺链。您可以看到代码返回函数的结果(将是Promise),并将其发送到链中的下一个函数。

代码不再嵌套,但看起来仍然很混乱!

通过使用箭头函数的功能,我们可以删除“包装器”功能。代码变得更清晰,但仍然有很多不必要的括号:

function printAll(){
  printString("A")
  .then(() => printString("B"))
  .then(() => printString("C"))
}
printAll()

Await

Await基本上是Promises的语法糖。它使您的异步代码看起来更像是同步/过程代码,人类更容易理解。

该PRINTSTRING功能不自许的版本在所有改变。

再次,让我们尝试按顺序打印字母A,B,C:

async function printAll(){
  await printString("A")
  await printString("B")
  await printString("C")
}
printAll()

是啊...。好多了!

您可能会注意到我们对包装函数printAll使用“async”关键字。这让我们的JavaScript知道我们正在使用async / await语法,如果你想使用Await,这是必要的。这意味着你不能在全球范围内使用Await; 它总是需要一个包装函数。大多数JavaScript代码都在函数内部运行,因此这不是什么大问题。

等等,这里还有更多哦

该PRINTSTRING函数不返回任何东西,是独立的,所有我们关心的是顺序。但是,如果您想获取第一个函数的输出,在第二个函数中执行某些操作,然后将其传递给第三个函数,该怎么办?

我们不是每次都打印字符串,而是创建一个连接字符串并传递它的函数。

Callbacks

这里是回调样式:

function addString(previous, current, callback){
  setTimeout(
    () => {
      callback((previous + '' '' + current))
    }, 
    Math.floor(Math.random() * 100) + 1
  )
}

为了使用它:

function addAll(){
  addString('''', ''A'', result => {
    addString(result, ''B'', result => {
      addString(result, ''C'', result => {
       console.log(result) // Prints out " A B C"
      })
    })
  })
}
addAll()

不太好。

Promises

这是Promise风格:

function addString(previous, current){
  return new Promise((resolve, reject) => {
    setTimeout(
      () => {
        resolve(previous + '' '' + current)
      }, 
      Math.floor(Math.random() * 100) + 1
    )
  })
}

为了使用它:

function addAll(){  
  addString('''', ''A'')
  .then(result => {
    return addString(result, ''B'')
  })
  .then(result => {
    return addString(result, ''C'')
  })
  .then(result => {
    console.log(result) // Prints out " A B C"
  })
}
addAll()

使用箭头函数意味着我们可以使代码更好一些:

function addAll(){  
  addString('''', ''A'')
  .then(result => addString(result, ''B''))
  .then(result => addString(result, ''C''))
  .then(result => {
    console.log(result) // Prints out " A B C"
  })
}
addAll()

这肯定更具可读性,特别是如果你向链添加更多,但仍然是一堆括号。

Await

该功能与Promise版本保持一致。

并且为了使用它:

async function addAll(){
  let toPrint = ''''
  toPrint = await addString(toPrint, ''A'')
  toPrint = await addString(toPrint, ''B'')
  toPrint = await addString(toPrint, ''C'')
  console.log(toPrint) // Prints out " A B C"
}
addAll()

Yeah. SO MUCH BETTER~

class.__mro__、class.mro()、class.__subclasses__()如何使用

class.__mro__、class.mro()、class.__subclasses__()如何使用

本篇内容介绍了“class.__mro__、class.mro()、class.__subclasses__()如何使用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

 

实验代码展示:

# class Person():# class Person(object):# class Person:class Person:  # class Person(object):  # class Person:  # class Person(): 这三种写法都是可以的
  '''定义基类Person'''
  def __init__(self, name, age):'''初始化属性name和age'''self.name = name
    self.age = age  def printInfo(self):print(  '---我是一个实例对象, 属于类型:{0:^35}   ---我的名字是: {1:{3}<8}   ---我的年龄是: {2:<5}'.format(str(self.__class__), str(self.name), str(self.age), chr(12288)  ))if __name__ == "__main__":print()per = Person('林麻子',15)per.printInfo()print('-'*50)print(Person.__mro__)print(Person.mro())print(Person.__subclasses__())print('*'*50)

控制台下执行结果:

Windows PowerShell
版权所有 (C) Microsoft Corporation。保留所有权利。

尝试新的跨平台 PowerShell https://aka.ms/pscore6

加载个人及系统配置文件用了 1016 毫秒。(base) PS C:\Users\chenxuqi\Desktop\News4cxq\test4cxq> conda activate ssd(ssd) PS C:\Users\chenxuqi\Desktop\News4cxq\test4cxq>  & 'D:\Anaconda3\envs\ssd\python.exe' 'c:\Users\chenxuqi\.vscode\extensions\ms-python.python-2020.12.424452561\pythonFiles\lib\python\debugpy\launcher' '63627' '--' 'c:\Users\chenxuqi\Desktop\News4cxq\test4cxq\test21.py'---我是一个实例对象, 属于类型:     <class '__main__.Person'>        ---我的名字是: 林麻子        ---我的年龄是: 15   
--------------------------------------------------(<class '__main__.Person'>, <class 'object'>)[<class '__main__.Person'>, <class 'object'>][]**************************************************(ssd) PS C:\Users\chenxuqi\Desktop\News4cxq\test4cxq>

“class.__mro__、class.mro()、class.__subclasses__()如何使用”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注小编网站,小编将为大家输出更多高质量的实用文章!

css – ‘div .class’,’.class’和’.class div’之间的差异

css – ‘div .class’,’.class’和’.class div’之间的差异

我有一个div:< div>

我注意到div.class处理这种风格,而.class div则没有.而且,.class也处理这种风格.

这是为什么 ?

解决方法

I notice that div.class handles this style,while .class div does not.

div.class查找具有类类的div.

.class div查找一个div,它是类类的元素的后代.

您的元素是具有类类的div,因此选择器不会选择它.

Moreover,.class handles the style as well.

.class将选择具有该类的任何元素,包括任何div元素.

css – “.class”和“.class,.class .class”之间的区别?

css – “.class”和“.class,.class .class”之间的区别?

以下摘自PrimeFaces文档,似乎在标题中描述的两个选择器之间存在差异:
.ui-widget,.ui-widget .ui-widget {
     font-size: 90% !important;
}

有人可以解释第二个选择器(“.ui-widget .ui-widget”)对我的意义吗?我理解,它匹配类“ui-widget”的元素,它们本身是同一类的其他元素的子元素,但不是那些已经由第一个选择器选择的元素?

解决方法

编辑:作为@Robin Kanters和其他人已经指出,与添加.class .class选择器 – 特异性有微小的差别。 (这可以看出 here)

否则.class .class选择器是多余的。

.ui-widget {
     font-size: 90% !important;
}

.ui-widget,.ui-widget .ui-widget {
     font-size: 90% !important;
}

产生相同的结果。

FIDDLE

你可以在上面的小提琴中看到单个.ui-widget选择器足以产生font-size的递归继承。

关于Python: callbacks and mix-in class的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于Callbacks, Promises and Async/Await、class.__mro__、class.mro()、class.__subclasses__()如何使用、css – ‘div .class’,’.class’和’.class div’之间的差异、css – “.class”和“.class,.class .class”之间的区别?等相关知识的信息别忘了在本站进行查找喔。

本文标签: