相关疑难解决方法(0)

在Python中使用静态方法有什么好处?

我在代码中遇到了python中的未绑定方法错误

class Sample(object):
'''This class defines various methods related to the sample'''

    def drawSample(samplesize,List):
        sample=random.sample(List,samplesize)
        return sample

Choices=range(100)
print Sample.drawSample(5,Choices)
Run Code Online (Sandbox Code Playgroud)

在这里阅读了很多有用的帖子之后,我想到了如何在上面添加@staticmethod以使代码正常工作.我是python新手.有人可以解释为什么人们想要定义静态方法吗?或者,为什么并非所有方法都定义为静态方法?

python

73
推荐指数
6
解决办法
3万
查看次数

函数,未绑定方法和绑定方法有什么区别?

我问这个问题是因为对这个答案的评论主题进行了讨论.我90%的方式来绕过它.

In [1]: class A(object):  # class named 'A'
   ...:     def f1(self): pass
   ...:
In [2]: a = A()  # an instance
Run Code Online (Sandbox Code Playgroud)

f1 存在三种不同的形式:

In [3]: a.f1  # a bound method
Out[3]: <bound method a.f1 of <__main__.A object at 0x039BE870>>
In [4]: A.f1  # an unbound method
Out[4]: <unbound method A.f1>
In [5]: a.__dict__['f1']  # doesn't exist
KeyError: 'f1'
In [6]: A.__dict__['f1']  # a function
Out[6]: <function __main__.f1>
Run Code Online (Sandbox Code Playgroud)

绑定方法,未绑定方法函数对象之间的区别是什么,所有这些都由f1描述?如何调用这三个对象?他们怎么能相互转化?关于这些东西的文档很难理解.

python oop methods function

57
推荐指数
2
解决办法
2万
查看次数

覆盖python中的静态方法

在这里参考关于python的绑定和未绑定方法的第一个答案,我有一个问题:

class Test:
    def method_one(self):
        print "Called method_one"
    @staticmethod
    def method_two():
        print "Called method_two"
    @staticmethod
    def method_three():
        Test.method_two()
class T2(Test):
    @staticmethod
    def method_two():
        print "T2"
a_test = Test()
a_test.method_one()
a_test.method_two()
a_test.method_three()
b_test = T2()
b_test.method_three()
Run Code Online (Sandbox Code Playgroud)

产生输出:

Called method_one
Called method_two
Called method_two
Called method_two
Run Code Online (Sandbox Code Playgroud)

有没有办法在python中覆盖静态方法?

我希望b_test.method_three()打印"T2",但它没有(打印"Called method_two"代替).

python static overriding

46
推荐指数
1
解决办法
2万
查看次数

如何在python中传递成员函数作为参数?

我想传递类似于成员函数指针的东西.我尝试了以下内容.

class dummy:
    def func1(self,name):
        print 'hello %s' % name
    def func2(self,name):
        print 'hi %s' % name

def greet(f,name):
    d = getSomeDummy()
    d.f(name)

greet(dummy.func1,'Bala')
Run Code Online (Sandbox Code Playgroud)

预期的产出是 hello Bala

python python-2.7

24
推荐指数
2
解决办法
2万
查看次数

如何在python中使用带有一个参数的super()

在阅读Python中的super()对象时,我阅读了以下语句:

如果省略第二个参数,则返回的超级对象是未绑定的

这究竟是什么意思,我如何super()在代码中使用一个参数?

python super

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

动态创建方法和装饰器,得到错误'functools.partial'对象没有属性'__module__'

我目前正在使用EndpointsModel为AppEngine上的所有模型创建RESTful API.由于它是RESTful,这些api有很多重复代码,我想避免

例如:

class Reducer(EndpointsModel):
    name = ndb.StringProperty(indexed=False)

@endpoints.api(
    name="bigdata",
    version="v1",
    description="""The BigData API""",
    allowed_client_ids=ALLOWED_CLIENT_IDS,
)
class BigDataApi(remote.Service):
    @Reducer.method(
        path="reducer",
        http_method="POST",
        name="reducer.insert",
        user_required=True,
    )
    def ReducerInsert(self, obj):
        pass

    ## and GET, POST, PUT, DELETE
    ## REPEATED for each model
Run Code Online (Sandbox Code Playgroud)

我想让它们变得通用.所以我尝试动态添加方法到类.到目前为止我尝试了什么:

from functools import partial, wraps

def GenericInsert(self, obj, cls):
    obj.owner = endpoints.get_current_user()
    obj.put()
    return obj

# Ignore GenericDelete, GenericGet, GenericUpdate ...

import types
from functools import partial

def register_rest_api(api_server, endpoint_cls):
    name = endpoint_cls.__name__

    # create list method 
    query_method = types.MethodType( …
Run Code Online (Sandbox Code Playgroud)

python google-app-engine functools google-cloud-endpoints endpoints-proto-datastore

18
推荐指数
2
解决办法
8256
查看次数

如何将函数作为类属性赋值成为Python中的方法?

>>> class A(object): pass
>>> def func(cls): pass
>>> A.func = func
>>> A.func
<unbound method A.func>
Run Code Online (Sandbox Code Playgroud)

这个赋值如何创建一个方法?对于类,赋值执行以下操作似乎不直观:

  • 将函数转换为未绑定的实例方法
  • 将函数包含在classmethod()类方法中(实际上,这非常直观)
  • 将函数包含在staticmethod()函数中

似乎第一个应该有一个instancemethod(),而对于最后一个,根本不应该有一个包装函数.我知道这些是用于class块内的用途,但为什么它们应用于它之外呢?

但更重要的是,如何将函数分配到一个类中?什么魔法可以解决这3件事?

更令人困惑的是:

>>> A.func
<unbound method A.func>
>>> A.__dict__['func']
<function func at 0x...>
Run Code Online (Sandbox Code Playgroud)

但我认为在检索属性时,这与描述符有关.我不认为这与设置属性有很大关系.

python class-method

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

类方法作为 scipy.optimize.curve_fit 的模型函数

说明书上有curve_fit说明

模型函数 f(x, ...)。它必须将自变量作为第一个参数,并将要拟合的参数作为单独的剩余参数。

但是,我想使用该类的方法作为模型函数,该方法定义为:

def model_fun(self,x,par):
Run Code Online (Sandbox Code Playgroud)

因此,如您所见,第一个参数不是自变量。有什么办法可以使用类的方法作为curve_fit的模型函数

python curve-fitting scipy

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

Python - 在地图中应用成员函数

我声明了一个类Employee和一个由它组成的列表:

class Employee():
    def __init__(self, _name):
        self.name = _name
    def get_name(self):
        return self.name

Tom   = Employee("Tom")
Karl  = Employee("Karl")
John  = Employee("John")

employee_list = [Tom, Karl, John]
Run Code Online (Sandbox Code Playgroud)

现在我想通过get_name在地图中应用来获得他们的名字列表:

name_list = map(get_name, employee_list)


Traceback (most recent call last): File "ask.py", line 13, in <module> 
    name_list = map(get_name, employee_list) 
NameError: name 'get_name' is not defined
Run Code Online (Sandbox Code Playgroud)

怎么可能get_name没有定义?

如何在地图中应用成员函数?

python dictionary

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

Python中@staticmethod的意义是什么?

我开发了这个简短的测试/示例代码,以更好地了解静态方法在Python中的工作方式。

class TestClass:
    def __init__(self, size):
        self.size = size

    def instance(self):
        print("regular instance method - with 'self'")

    @staticmethod
    def static():
        print("static instance method - with @staticmethod")

    def static_class():
        print("static class method")


a = TestClass(1000)

a.instance()
a.static()
TestClass.static_class()
Run Code Online (Sandbox Code Playgroud)

该代码正常工作,不会返回任何错误。我的问题是:

  1. 我是否正确理解“自我”可以理解为类似于“将从实例中调用此方法”?

  2. 再说一遍,@ staticmethod背后的逻辑是什么?是否可以创建可以从实例调用的静态方法?不就是没有什么静态方法是什么?

  3. 为什么第二种方法比第三种方法更受青睐?(我假设装饰器存在,所以有一点要注意。)第三个选项似乎更简单,直接。

python static-methods

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