相关疑难解决方法(0)

__getattr__与__getattribute__之间的区别

我想知道何时使用__getattr____getattribute__.该文件提到了__getattribute__适用于新样式类.什么是新式课程?

python getattr getattribute

378
推荐指数
8
解决办法
12万
查看次数

__getattr__和getattr之间有什么关系?

我知道这段代码是对的:

class A:   
    def __init__(self):
        self.a = 'a'  
    def method(self):   
        print "method print"  

a = A()   
print getattr(a, 'a', 'default')   
print getattr(a, 'b', 'default')  
print getattr(a, 'method', 'default') 
getattr(a, 'method', 'default')()   
Run Code Online (Sandbox Code Playgroud)


这是错的:

# will __getattr__ affect the getattr?

class a(object):
    def __getattr__(self,name):
        return 'xxx'

print getattr(a)
Run Code Online (Sandbox Code Playgroud)

这也是错的:

a={'aa':'aaaa'}
print getattr(a,'aa')
Run Code Online (Sandbox Code Playgroud)


我们应该在哪里使用这些功能(__getattr__getattr)?

python getattr

31
推荐指数
3
解决办法
1万
查看次数

扩展类(Monkey Patching)如何在Python中工作?

class Foo(object):
  pass

foo = Foo()
def bar(self):
  print 'bar'

Foo.bar = bar
foo.bar() #bar
Run Code Online (Sandbox Code Playgroud)

来自JavaScript,如果"类"原型增加了某个属性.众所周知,该"类"的所有实例在其原型链中都具有该属性,因此不必对其任何实例或"子类"进行修改.

从这个意义上说,像Python这样的基于类的语言如何实现Monkey补丁?

python oop monkeypatching object

12
推荐指数
2
解决办法
1100
查看次数

在 Python 中使用 __getattr__ 重载运算符

我试图使用该__getattr__函数同时重载多个运算符。在我的代码中,如果我调用foo.__add__(other)它,它会按预期工作,但是当我尝试时foo + bar,它不会。这是一个最小的例子:

class Foo():
    
    
    def add(self, other):
        return 1 + other
    
    def sub(self, other):
        return 1 - other
    
    def __getattr__(self, name):
                
        stripped = name.strip('_')
        if stripped in {'sub', 'add'}:
            return getattr(self, stripped)
        else:
            return
    
if __name__=='__main__':
    
    bar = Foo()
    
    print(bar.__add__(1)) # works
    print(bar + 1) # doesn't work
Run Code Online (Sandbox Code Playgroud)

__add__我意识到在此示例中仅定义和会更容易__sub__,但在我的情况下这不是一个选项。

另外,作为一个小问题,如果我替换该行:

if stripped in {'sub', 'add'}:
Run Code Online (Sandbox Code Playgroud)

if hasattr(self, name):
Run Code Online (Sandbox Code Playgroud)

代码可以运行,但随后我的 iPython 内核崩溃了。为什么会发生这种情况以及如何预防?

python

5
推荐指数
1
解决办法
541
查看次数

Flask的会话对象是字典还是对象?

我注意到我可以将session对象视为object(session.myVal = 'foo')以及dict(session['myVal'] = 'foo').您无法使用带有对象语法的dict语法访问值集,反之亦然.使用会话对象的正确方法是什么?

python flask

1
推荐指数
1
解决办法
1823
查看次数

标签 统计

python ×5

getattr ×2

flask ×1

getattribute ×1

monkeypatching ×1

object ×1

oop ×1