相关疑难解决方法(0)

什么是“可继承的替代构造函数”?

我在这个答案中偶然发现了术语“可继承的替代构造函数”:/sf/answers/116866711/

该链接指向一个classmethod进行解释的地方。

其他编程语言也有这个功能吗?

python inheritance class-method

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

如何在python中引用重写类函数

我知道C++和Java,我不熟悉Pythonic编程.所以也许这是我想要做的坏风格.

考虑下面的例子:

class foo:
        def a():
                __class__.b() # gives: this is foo
                bar.b() # gives: this is bar
                foo.b() # gives: this is foo
                # b() I'd like to get "this is bar" automatically

        def b():
                print("this is foo")

class bar( foo ):
        def b( ):
                print("this is bar")

bar.a()
Run Code Online (Sandbox Code Playgroud)

请注意,我没有使用self参数,因为我没有尝试创建类的实例,因为不需要我的任务.我只是试图以一种可以覆盖函数的方式引用函数.

python oop inheritance class-method static-functions

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

Python说我向我的函数传递了太多参数?

我有一些python代码包含如下所示的单元测试:

class SunCalcTestCases(unittest.TestCase):
    """Tests for `suncalc.py`."""
    def near(val1, val2):
        return abs(val1 - val2) < (margin or 1E-15)

    def test_getPositions(self):
        """Get sun positions correctly"""
        sunPos = suncalc.getPosition(self.date, self.lat, self.lng)
        az = sunPos["azimuth"]
        res = self.near(az, -2.5003175907168385) 
Run Code Online (Sandbox Code Playgroud)

但是当我运行这个时,我得到错误:

Traceback (most recent call last):
  File "test.py", line 64, in test_getPositions
    res = self.near(az, -2.5003175907168385)
TypeError: near() takes exactly 2 arguments (3 given)
Run Code Online (Sandbox Code Playgroud)

我是python的新手,所以我很抱歉,如果我在这里遗漏了一些东西,但据我所知,我在调用函数时只传递了两个参数: self.near(az, -2.5003175907168385)

谁能告诉我为什么它认为我传递了3个参数?

python python-2.7

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

如何在枚举中添加方法?

我想在我的枚举中添加一个方法.

class Kerneltype(Enum):
    tube = 0
    subspace_KDE = 1
    deltashift = 2
    dist_sens_via_mass_1 = 3

    def aslist(self):
        return [self.tube, self.subspace_KDE, self.deltashift, self.dist_sens_via_mass_1]

    def fromint(self, int):
        return self.aslist()[int]
Run Code Online (Sandbox Code Playgroud)

不起作用.代替

Kerneltype.aslist()
Run Code Online (Sandbox Code Playgroud)

我目前要做的

[kt[1] for kt in ob.Kerneltype.__members__.items()]
Run Code Online (Sandbox Code Playgroud)

python enums

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

如何在Python中的类中使用静态变量

class Cls:
    counter = 0
    def __init__(self, name):
        self.name = name
        self.counter += 1
    def count(self):
        return self.counter
Run Code Online (Sandbox Code Playgroud)

我正在学习python,我想要的是一个静态计数器,它计算类实例化的次数,但每次创建实例时counter都会重新创建并且count()函数总是返回1.我想要一些java中的东西看起来像这样

public class Cls {
    private static int counter = 0;
    private String name;
    public Cls(String name) {
        this.name = name;
        counter ++;
    }
    public static int count(){
        return counter;
    }
}
Run Code Online (Sandbox Code Playgroud)

python python-3.x

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

无法在另一个静态方法中调用静态方法

我有一个具有静态方法的类,我想在该类中使用另一个静态方法来调用该方法,但它返回NameError: name ''method_name' is not defined

我正在尝试做的事情的例子。

class abc():
    @staticmethod
    def method1():
        print('print from method1')

    @staticmethod
    def method2():
        method1()
        print('print from method2')

abc.method1()
abc.method2()
Run Code Online (Sandbox Code Playgroud)

输出:

print from method1
Traceback (most recent call last):
  File "test.py", line 12, in <module>
    abc.method2()
  File "test.py", line 8, in method2
    method1()
NameError: name 'method1' is not defined
Run Code Online (Sandbox Code Playgroud)

解决这个问题的最佳方法是什么?

我想将代码保留为这种格式,其中有一个类包含这些静态方法并使它们能够相互调用。

python methods static-methods

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

在python中调用类方法

我想从不同的类调用python中的方法,如下所示:

class foo():
    def bar(name):
        return 'hello %s' % name

def hello(name):
    a = foo().bar(name)
    return a
Run Code Online (Sandbox Code Playgroud)

hello('world')将返回'Hello World'.我知道我在这里做错了什么,有谁知道它是什么?我想这可能是我处理课程的方式,但我还没有理解它.

python methods

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

这个全局类变量如何符合pep8并仍然有效?

Pep8建议始终使用cls类方法定义的第一个参数.现在假设我想使用一个类变量(在这种情况下:) cls.cartridge_state,它也可以在实例方法中使用(在这种情况下:) __init__.因此,我需要将变量设为全局变量(请参阅下面的代码).但实例化会FountainPen生成以下运行时错误:

self.cartridge_state = cls.cartridge_state
NameError: global name 'cls' is not defined
Run Code Online (Sandbox Code Playgroud)

但是,有一次,当我改变global cartridge_stateglobal cls.cartridge_state我得到一个SyntaxError当我尝试导入模块.

class FountainPen(object):
    cartridge_ink = "water-based"
    @classmethod
    def toggle_default_cartridge_state(cls):
        i = 0
        cartridge_states = ['non-empty','empty']
        global cartridge_state
        cls.cartridge_state = cartridge_states[i]
        i += 1

    def __init__(self):
        self.cartridge_state = cls.cartridge_state
        global number_of_refills
        self.number_of_refills = 0

    def write(self):
        print Pen.write(self)
        self.cartridge_state = "empty"
        return self.cartridge_state

    def refill(self):
        self.cartridge_state = "non-empty"
        self.number_of_refills += 1
Run Code Online (Sandbox Code Playgroud)

如何让类变量cartridge_state符合pep8并使此代码正常工作?

python variables class pep8

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

python中的未绑定变量

我正在尝试在python中制作一个玩具单例来学习语言的来龙去脉,并且遇到了python如何工作的问题.我宣布这样的课程

class ErrorLogger:
  # Singleton that provides logging to a file  
  instance = None

  def getInstance():
    # Our singleton "constructor"
    if instance is None :
      print "foo"
Run Code Online (Sandbox Code Playgroud)

我打电话的时候

log = ErrorLogger.getInstance()
Run Code Online (Sandbox Code Playgroud)

我明白了

 File "/home/paul/projects/peachpit/src/ErrorLogger.py", line 7, in getInstance
    if instance is None :
 UnboundLocalError: local variable 'instance' referenced before assignment
Run Code Online (Sandbox Code Playgroud)

这里发生了什么,不应该静态分配Null?这样做的正确方法是什么?

python

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

类Python中的装饰器

对不起我的英语不好.我想创建一个装饰器方法,可以检查每个步骤方法并将其写入db.

这是我的方法:

class Test:

    @StepStatusManager.logger_steps("GET_LIST") # TypeError: logger_steps() missing 1 required positional argument: 'type'
    def get_mails(self):
       print("GET_MAIL")    
Run Code Online (Sandbox Code Playgroud)

这是我的装饰类:

class StepStatusManager:

    def __init__(self):
        self.db = DB()

    def logger_steps(self, type):
        def logger_steps(func):
            @functools.wraps(func)
            def wrapper(*args):
                try:
                    func(*args)
                    self.db.setStatus(type)
                except BaseException as e:
                    print(e)

            return wrapper

        return logger_steps
Run Code Online (Sandbox Code Playgroud)

python decorator

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