相关疑难解决方法(0)

为什么Python 3.x的超级()魔术?

在Python 3.x中,super()可以不带参数调用:

class A(object):
    def x(self):
         print("Hey now")

class B(A):
    def x(self):
        super().x()
Run Code Online (Sandbox Code Playgroud)
>>> B().x()
Hey now
Run Code Online (Sandbox Code Playgroud)

为了使这项工作,一些编译时间魔法进行,其中的一个后果是,下面的代码(重新绑定supersuper_)失败:

super_ = super

class A(object):
    def x(self):
        print("No flipping")

class B(A):
    def x(self):
        super_().x()
Run Code Online (Sandbox Code Playgroud)
>>> B().x()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in x
RuntimeError: super(): __class__ cell not found
Run Code Online (Sandbox Code Playgroud)

super()如果没有编译器的帮助,为什么无法在运行时解析超类?是否存在这种行为或其潜在原因可能会让一个不知情的程序员陷入困境的实际情况?

...并且,作为一个附带问题:在Python中是否有任何其他函数,方法等示例可以通过将它们重新绑定到不同的名称来打破?

python super python-3.x

153
推荐指数
1
解决办法
4万
查看次数

什么时候应该使用@classmethod和def方法(自我)?

在集成我之前没有使用的Django应用程序时,我发现了两种不同的方法来定义类中的函数.作者似乎非常故意地使用它们.第一个是我自己经常使用的一个:

class Dummy(object):

    def some_function(self,*args,**kwargs):
        do something here
        self is the class instance
Run Code Online (Sandbox Code Playgroud)

另一个是我不使用的,主要是因为我不明白何时使用它,以及为什么:

class Dummy(object):

    @classmethod
    def some_function(cls,*args,**kwargs):
        do something here
        cls refers to what?
Run Code Online (Sandbox Code Playgroud)

在Python文档中,classmethod装饰器用这句话解释:

类方法接收类作为隐式的第一个参数,就像实例方法接收实例一样.

所以我猜cls是指Dummy自己(class不是实例).我不完全理解为什么会这样,因为我总能做到这一点:

type(self).do_something_with_the_class
Run Code Online (Sandbox Code Playgroud)

这只是为了清楚起见,还是我错过了最重要的部分:如果没有它,那些怪异而迷人的东西是无法完成的?

python language-details method-dispatch class-method language-lawyer

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

Python类方法的示例用例是什么?

我已经阅读了Python中的什么类方法?但那篇文章中的例子很复杂.我正在寻找Python中类方法的特定用例的清晰,简单,简单的例子.

您能说出一个小的,具体的示例用例,其中Python类方法将是该工作的正确工具吗?

python class class-method

59
推荐指数
5
解决办法
4万
查看次数

我们可以拥有静态虚函数吗?如果没有,那么为什么?

可能重复:
C++静态虚拟成员?

我们可以拥有静态虚函数吗?如果没有,那么为什么?

class X
{
public:
       virtual static void fun(){} // Why we cant have static virtual function in C++?
};
Run Code Online (Sandbox Code Playgroud)

c++ static-methods virtual-functions

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

classmethod在这段代码中做了什么?

在django.utils.tree.py中:

def _new_instance(cls, children=None, connector=None, negated=False):
        obj = Node(children, connector, negated)
        obj.__class__ = cls
        return obj
    _new_instance = classmethod(_new_instance)
Run Code Online (Sandbox Code Playgroud)

我不知道classmethod这段代码中的内容是什么.有人可以解释它的作用以及如何使用它吗?

python

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

python:如何从其中引用类(如递归函数)

对于递归函数,我们可以这样做:

def f(i):
  if i<0: return
  print i
  f(i-1)

f(10)
Run Code Online (Sandbox Code Playgroud)

但有没有办法做以下事情?

class A:
  # do something
  some_func(A)
  # ...
Run Code Online (Sandbox Code Playgroud)

python class

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

我为什么要在python中使用classmethod?

我在python中的某个类中编写了一个函数,人们建议我向这个函数添加一个@classmethod装饰器.

我的代码:

import random


class Randomize:
    RANDOM_CHOICE = 'abcdefg'

    def __init__(self, chars_num):
        self.chars_num = chars_num

    def _randomize(self, random_chars=3):
        return ''.join(random.choice(self.RANDOM_CHOICE)
                       for _ in range(random_chars))
Run Code Online (Sandbox Code Playgroud)

建议的更改:

    @classmethod
    def _randomize(cls, random_chars=3):
        return ''.join(random.choice(cls.RANDOM_CHOICE)
                       for _ in range(random_chars))
Run Code Online (Sandbox Code Playgroud)

我几乎总是只使用这个_randomize功能.

我的问题是:添加到classmethod装饰器的功能有什么好处?

python decorator class-method

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

独立的功能或方法

我需要以一种方式处理类的两个对象,它将返回同一个类的第三个对象,并且我试图确定是否更好地将它作为一个独立的函数来接收两个对象并返回第三个或作为一种方法,它将采取另一个对象并返回第三个.


举个简单的例子.这会是:

from collections import namedtuple

class Point(namedtuple('Point', 'x y')):
    __slots__ = ()
    #Attached to class
    def midpoint(self, otherpoint):
        mx = (self.x + otherpoint.x) / 2.0
        my = (self.y + otherpoint.y) / 2.0
        return Point(mx, my)

a = Point(1.0, 2.0)
b = Point(2.0, 3.0)

print a.midpoint(b)
#Point(x=1.5, y=2.5)
Run Code Online (Sandbox Code Playgroud)

或这个:

from collections import namedtuple

class Point(namedtuple('Point', 'x y')):
    __slots__ = ()


#not attached to class
#takes two point objects
def midpoint(p1, p2):
    mx = (p1.x + p2.x) / 2.0
    my = …
Run Code Online (Sandbox Code Playgroud)

python api readability

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

这个方法应该是一个类方法,为什么它不能访问变量?

我来自java背景,所以我在这里有点困惑。

考虑下面的代码片段:

class A():
    def __init__(self, **kwargs):
        self.obj_var = "I am obj var"

    @classmethod
    def class_method(cls):
        print cls.obj_var   # this line is in question here
        cls.cls_obj = "I m class object"
        return cls.cls_obj
Run Code Online (Sandbox Code Playgroud)

这会引发错误:

In [30]: a = A()

In [31]: a.obj_var
Out[31]: 'I am obj var'

In [32]: a.class_method()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-32-3dcd9d512548> in <module>()
----> 1 a.class_method()

<ipython-input-29-9c0d341ad75f> in class_method(cls)
      8     @classmethod
      9     def class_method(cls):
---> 10         print cls.obj_var
     11         cls.cls_obj = "I m …
Run Code Online (Sandbox Code Playgroud)

python instance-variables decorator class-method python-decorators

6
推荐指数
2
解决办法
6161
查看次数

在Python中定义类方法的多种方法?

在Dive Into Python中,Mark Pilgrim说:

定义类方法时,必须将self显式列为每个方法的第一个参数

然后他在代码中给出了一些这样的例子:

def clear(self): self.data.clear()
def copy(self):
    if self.__class__ is UserDict:
        return UserDict(self.data)
    import copy
    return copy.copy(self)
Run Code Online (Sandbox Code Playgroud)

在网上浏览一些Python代码时,我遇到了@classmethod装饰者.一个例子是:

class Logger:
    @classmethod
    def debug(msg):
        print "DEBUG: " + msg
Run Code Online (Sandbox Code Playgroud)

(注意函数中没有self参数debug)

使用self第一个参数和使用@classmethod装饰器定义类方法有什么不同吗?如果没有,是一种定义更常用/优先的类方法的方法吗?

python methods class

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

在python中使用@classmethod有什么用以及何时使用?

我从来没有使用过@classmethod,也没有想到任何使用它的例子,我知道它是如何工作的,但我不知道什么时候使用它

class Example:
    def __init__(self,param1,param2):
        self.param1 = param1
        self.param2 = param2
    @classmethod
    def my_method(cls,param1,param2):
        return cls(param1,param2)

example = Example.my_method(1,2)
print(example)
Run Code Online (Sandbox Code Playgroud)

输出:

<__main__.Example object at 0x02EC57D0>
Run Code Online (Sandbox Code Playgroud)

但为什么不这样做呢?

class Example:
    def __init__(self,param1,param2):
        self.param1 = param1
        self.param2 = param2

    def my_method(self,param1,param2):
        return Example(param1,param2)

example = Example(1,2)
method = example.my_method(3,4)
print(method)
Run Code Online (Sandbox Code Playgroud)

输出:

<__main__.Example object at 0x02EC57D0>
Run Code Online (Sandbox Code Playgroud)

这是相同的结果,但是当我可以使用 classmethod 时它不会出现在我的脑海中

python decorator python-decorators

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

如何在课外使用方法?

我正在上python课程.我已经在论坛上询问过这方面的提示,但没有运气.我认为我的实施非常糟糕.我对此非常陌生,所以请耐心等待,即使我提出问题的方式.

上面的问题是我被告知需要做的事情.我试过没有运气,所以我来这里寻求帮助.

最终,我试图让我的主要处理程序回应我的按键.我以前做过这个,但我们还没有上课.这就是障碍所在.我应该实现类方法/变量来使它们工作,而不是使用新变量或新的全局变量.

例如

class SuchAndSuch:

    def __init__(self, pos, vel, ang, ang_vel, image, info, sound = None):
        self.pos = [pos[0],pos[1]]
        self.vel = [vel[0],vel[1]]
        self.angle = ang
        self.angle_vel = ang_vel
        self.image = image

    def update(self):
        # this is where all the actual movement and rotation should happen
        ...
Run Code Online (Sandbox Code Playgroud)

下面的处理程序在SuchAndSuch类之外:

def keydown(key):
    # need up left down right buttons
    if key == simplegui.KEY_MAP["up"]:
        # i'm supposed to just call methods here to make the keys respond???

    ...
Run Code Online (Sandbox Code Playgroud)

因此,所有更新都应该发生在SuchAndSuch类中,并且 …

python class

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