以下类方法有什么区别?
是一个是静态而另一个不是?
class Test(object):
def method_one(self):
print "Called method_one"
def method_two():
print "Called method_two"
a_test = Test()
a_test.method_one()
a_test.method_two()
Run Code Online (Sandbox Code Playgroud) 在Python中,有没有办法绑定未绑定的方法而不调用它?
我正在编写一个wxPython程序,对于某个类,我认为将所有按钮的数据组合在一起作为类级别的元组列表是很好的,如下所示:
class MyWidget(wx.Window):
buttons = [("OK", OnOK),
("Cancel", OnCancel)]
# ...
def Setup(self):
for text, handler in MyWidget.buttons:
# This following line is the problem line.
b = wx.Button(parent, label=text).Bind(wx.EVT_BUTTON, handler)
Run Code Online (Sandbox Code Playgroud)
问题是,由于所有的值handler都是未绑定的方法,我的程序在一个壮观的火焰中爆炸,我哭泣.
我在网上寻找解决方案似乎应该是一个相对简单,可解决的问题.不幸的是我找不到任何东西.现在,我正在functools.partial尝试解决这个问题,但有没有人知道是否有一种干净,健康,Pythonic的方式将未绑定的方法绑定到一个实例并继续传递它而不调用它?
我正在使用Code Academy的Python教程,我对方法和函数的定义有点困惑.从教程:
你已经知道了一些我们所使用(或创建)字符串的内置功能,例如
.upper(),.lower(),str(),和len().
从C++来了,我想.upper()和.lower()将调用的方法和len()和str()功能.在本教程中,这些术语似乎可以互换使用.
Python是否以C++的方式区分方法和函数?
与方法和函数之间的差异不同,我问的是Python的细节.术语"方法"和"功能"似乎并不总是遵循链接问题的已接受答案中给出的定义.
例如,我尝试了类似的东西mydict = {'funcList1': [foo(),bar(),goo()], 'funcList2': [foo(),goo(),bar()],但是没有用.
有这种功能的某种结构吗?
我意识到我可以用一堆def语句轻松地做到这一点:
def func1():
foo()
bar()
goo()
Run Code Online (Sandbox Code Playgroud)
但是我需要的陈述数量变得非常笨拙且难以记住.将它们很好地包装在字典中会很好,我可以一次又一次地检查键.
将类中的方法用作生成器是否可接受/ Pythonic?我找到的所有示例都在函数中显示yield语句,而不是在类中.
这是一个示例工作代码:
class SomeClass(object):
def first_ten(self):
for i in range(10):
yield i
def test(self):
for i in self.first_ten():
print i
SomeClass().test()
Run Code Online (Sandbox Code Playgroud) 我知道我可以将一个函数附加到一个类并使其成为一个方法:
>>> def is_not_bound(inst, name):
... print("Hello %s" % name)
...
>>>
>>> class NoMethods:
... pass
...
>>>
>>> setattr(NoMethods, 'bound', is_not_bound)
>>>
>>> NoMethods().bound("oz") # prints: Hello oz
Hello oz
Run Code Online (Sandbox Code Playgroud)
令我惊讶的是,这也适用于从一个类到另一个类的绑定方法:
>>> class Foo:
... def foo(self, name):
... print("Hello %s" % name)
...
>>> class B:
... pass
...
>>> setattr(B, 'bound_to_b', getattr(Foo, 'foo'))
>>> B().bound_to_b("confused?")
Hello confused?
>>>
Run Code Online (Sandbox Code Playgroud)
我能安全地使用它吗?有什么我在监督的吗?
我发现的一个警告:
>>> B.bound_to_b
<function Foo.foo at 0x7fc997e8b730>
Run Code Online (Sandbox Code Playgroud)
虽然我从B调用了这个方法,但它似乎与Foo有关.
而且更令人惊讶的是:
>>> def new_method(self, addto):
... return self.num …Run Code Online (Sandbox Code Playgroud) 我想解决一个倒数问题。
这是我的递归函数,为什么Python3抱怨我的函数未定义?有什么想法吗?
class Solution:
def reverse(self, x: int) -> int:
if x < 0:
return -1 * reverse(self, x)
if x // 10 == 0:
return x
if x % 10 == 0:
return reverse(self, x // 10)
else:
return (x % 10) * 10 ** (len(str(x//10))) + reverse(self, x // 10)
Run Code Online (Sandbox Code Playgroud)
我只是遵循传统的递归函数。
我的问题有点类似于这个问题; 它涉及对象方法而不是模块内容.我想知道我是否可以使用该inspect模块来获取仅在我询问的类中定义的方法,而不是它的父级.
我需要这个,因为我的子类定义了'宏'方法,它在更高的抽象级别访问父方法,我不希望用户不得不担心在继承中一直定义的低级方法树.
这是一个简化的例子:
class Foo(object):
def __init__(self): pass
def f1(self): return 3
def f2(self): return 1
class Bar(Foo):
def __init__(self): Foo.__init__(self)
def g1(self): return self.f1() + self.f2()
def g2(self): return self.f1() - self.f2()
import inspect
inspect.getmembers(Bar, inspect.ismethod)
Run Code Online (Sandbox Code Playgroud)
输出:
[('__init__', <unbound method Bar.__init__>),
('f1', <unbound method Bar.f1>),
('f2', <unbound method Bar.f2>),
('g1', <unbound method Bar.g1>),
('g2', <unbound method Bar.g2>)]
Run Code Online (Sandbox Code Playgroud)
用户不需要知道或关心fs 的存在,因为她只对gs 有兴趣.(当然,这个输出在绝大多数上下文中都是有意义的,因为所有这些方法在实例化时都会被绑定到对象.)对于一个长继承树,返回的列表可以变得很长并且充满了所有的东西.与用户无关.
我怎样才能得到它离开f1并f2关闭这个名单?是否有类似于__module__类中定义的方法的属性?更好的是,是否可以使用实例 …
以此代码为例:
class SomeClass():
def a_method(self):
pass
print(SomeClass.a_method is SomeClass.a_method) # Example 1: False
print(SomeClass.a_method == SomeClass.a_method) # Example 2: True
print(SomeClass().a_method is SomeClass().a_method) # Example 3: False
print(SomeClass().a_method == SomeClass().a_method) # Example 4: False
Run Code Online (Sandbox Code Playgroud)
我写了一段代码来确定一个典型的回文字符串.我通过返回字符串的reverse()方法的定义来做到这一点.我也渴望拥有相同的方法,但是在虚空形式中,因为未来的某些需求.当我将后者添加到代码中时,有效输出将变为无效.所以,问题是定义两个具有相同名称但返回类型不同的方法是否合法?如果没有,请让我知道如何使用void-type方法编写此代码.
class detector(object):
def __init__(self,string):
self.string = string
forbidden = (' ','!','?','.','-','_','&','%',"#",",")
def eliminator(self):
for item in self.forbidden:
if item in self.string:
self.string = self.string.replace(item,"")
def reverse(self):
return self.string[::-1]
#def reverse(self):
# self.string = self.string[::-1] I am prone to add this method
def check(self):
reversed = self.reverse()
if self.string == reversed:
print("Yes")
else:
print("No")
det = detector("rise to vote, sir!")
det.eliminator()
det.check()
Run Code Online (Sandbox Code Playgroud)
当我添加注释行时,有效的"是"变为"否"!
class _GhostLink(object):
toGhost = lambda filename: False
class _Mod_AllowGhosting_All(_GhostLink):
def _loop(self):
# ...
if self.__class__.toGhost(fileName) != oldGhost:...
Run Code Online (Sandbox Code Playgroud)
产生:
class _GhostLink(object):
toGhost = lambda filename: False
class _Mod_AllowGhosting_All(_GhostLink):
def _loop(self):
# ...
if self.__class__.toGhost(fileName) != oldGhost:...
Run Code Online (Sandbox Code Playgroud)
同时传递一个实例,if self.toGhost(fileName) != ...结果如下:
Traceback (most recent call last):
File "bash\basher\mod_links.py", line 592, in Execute
changed = self._loop()
File "bash\basher\mod_links.py", line 587, in _loop
if self.__class__.toGhost(fileName) != oldGhost:
TypeError: unbound method <lambda>() must be called with _Mod_AllowGhosting_All instance as first argument (got Path …Run Code Online (Sandbox Code Playgroud) 我做了一点实验.通过检查__dict__类或实例,我可以看到某些方法有类型function和一些bound method.实验很乱,我无法解决以下问题.
在Python 3中,类或实例的方法之间有什么区别,它们是"函数",哪些是"绑定方法"?
它们是如何分别创建的?
它们可以在类和实例上调用吗?它们是否会被隐含地作为第一个参数的实例?
"绑定方法"是类的属性还是类的实例?
谢谢.
来自3.数据模型:
\n\n\n实例方法
\n实例方法对象组合了类、类实例和任何\n可调用对象(通常是用户定义的\xef\xac\x81ned 函数)。
\n
如果是定义的话,它的含义是什么?
\n如果不是定义,那么“实例方法”的定义是什么?
\n“实例方法”与类的方法是同一概念吗?
\n既然有人提出了类方法和静态方法、绑定方法和非绑定方法,那么我澄清一下:
\n我理解类的方法可以是普通方法、类方法或静态方法。我了解通过类或其实例访问的类的方法可以被绑定或函数。我从未听说过“实例方法”。即使看了引用,我也不知道它是什么,也不确定它是否与普通方法、类方法、静态方法、绑定方法或函数相关。
\npython ×13
methods ×4
python-3.x ×4
class ×2
function ×2
oop ×2
python-2.7 ×2
bind ×1
class-method ×1
dictionary ×1
dispatch ×1
generator ×1
inspect ×1
lambda ×1
object ×1
recursion ×1
reverse ×1