标签: class-method

调用类作用域中定义的 lambda 方法(作为类属性)

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)

python lambda class-method python-2.7

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

如何使用 Python 类属性作为 @Classmethod 的默认值?

看看下面的代码。

我想使用 的值a作为cclassmethod 声明中参数的默认值my_method()

我该怎么做?下面的例子失败了。

>>> class X:
...     a = 'hello'
...     def __init__(self, b):
...         self.b = b
...     @classmethod
...     def my_method(cls, c=X.a):
...         print 'cls.a = {}'.format(cls.a)
...         print 'c = {}'.format(c)
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in X
NameError: name 'X' is not defined
Run Code Online (Sandbox Code Playgroud)

python class-method class-attributes

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

根据类模板参数启用成员函数重载

这可能是一个愚蠢的问题,但我可以以某种方式使用没有模板参数的 require 子句吗?我有以下案例:

演示

#include <concepts>
#include <iostream>

template <typename T>
struct entity {
    requires (std::same_as<T, int>) 
    auto operator=(const entity&) { std::cout << "with T == int" << std::endl; return *this; }

    auto operator=(const entity&) { std::cout << "all else" << std::endl; return *this; }
};
Run Code Online (Sandbox Code Playgroud)

我想基于类模板参数而不是方法模板参数启用一个重载。我如何内联并使用概念来做到这一点?

c++ templates class-method c++20

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

Python在运行时添加方法

我正在尝试在运行时动态地向类添加方法,并且看到一些问题:

#Here we define a set of symbols within an exec statement and put them into the dictionary d
d = {}
exec "def get_%s(self): return self.%s" % (attr_name, attr) in d

#Now, we bind the get method stored in d['get_%s'] to our object (class)
func = d['get_%s' % (attr_name)].__get__(d['get_%s' % (attr_name)], class)
setattr(class_instance, func.__name__, func)
Run Code Online (Sandbox Code Playgroud)

当我尝试调用生成的get方法时,我看到如下:

Traceback (most recent call last):
  File "Textere_AdvancedExample.py", line 77, in <module>
    count = fact.get_counter()
  File "<string>", line 1, in get_counter
AttributeError: 'function' object …
Run Code Online (Sandbox Code Playgroud)

python methods class class-method

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

使用self访问类方法和变量

在下面的示例中,Test类有两个实例方法和一个classmethod

set_cls_var_1方法中,我使用self设置类变量.

set_cls_var_2方法中,我使用self调用类方法.

   class Test():

        #class variable
        cls_var = 10

        def __init__(self):
           obj_var=20

        def set_cls_var_1(self,val):
            #second method to access class variable
            print "first "
            self.cls_var = val

        def set_cls_var_2(self):
            print "second"
            self.task(200)

        @classmethod
        def task(cls,val):
            cls.cls_var = val


t=Test()

#set class variable by first method
t.set_cls_var_1(100)

print Test.cls_var

#set class variable by second method
t.set_cls_var_2()

print Test.cls_var
Run Code Online (Sandbox Code Playgroud)

产量

first 
10
second
200
Run Code Online (Sandbox Code Playgroud)

预期产出

first 
100
second
200
Run Code Online (Sandbox Code Playgroud)

我的问题是:为什么只有classmethod可以自己调用,为什么不是类变量

python class class-method class-variables python-2.7

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

为什么通过装饰器与类主体在class .__ slots__分配中存在差异?

我正在一个装饰器上实现不可变类的某些行为。我想要一个从namedtuple继承的类(具有属性不变性),并且还想添加一些新方法。像这样 ...但是正确防止将新属性分配给新类。

从namedtuple继承时,应定义__new__并设置__slots__为空元组(以保持不变性):

def define_new(clz):
    def __new(cls, *args, **kwargs):
        return super(clz, cls).__new__(cls, *args, **kwargs)

    clz.__new__ = staticmethod(__new) # delegate namedtuple.__new__ to namedtuple
    return clz

@define_new
class C(namedtuple('Foo', "a b c")):
    __slots__ = () # Prevent assignment of new vars
    def foo(self): return "foo"

C(1,2,3).x = 123 # Fails, correctly
Run Code Online (Sandbox Code Playgroud)

太好了 但是现在我想将__slots__任务移到装饰器中:

def define_new(clz):
    def __new(cls, *args, **kwargs):
        return super(clz, cls).__new__(cls, *args, **kwargs)

    #clz.__slots__ = ()
    clz.__slots__ = (123) # just for testing

    clz.__new__ …
Run Code Online (Sandbox Code Playgroud)

python decorator class-method namedtuple

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

可以将类方法创建为非装饰器吗?

假设我有以下课程:

class Item:
    def __init__(self, string=''):
        self.string = string
    @classmethod
    def from_string(cls, string):
        return cls(string=string)
Run Code Online (Sandbox Code Playgroud)

上述情况下的classmethod并不是必需的,因为我可以轻松地调用Item(string='asdf')而不是Item.from_string(string='asdf'),但是我只是以它为例。

是否有可能连接任意类方法的类本身以外?例如,类似:

def from_string(cls, string):
    return cls(string=string)

classmethod(from_string(Item, "asdf"))
Run Code Online (Sandbox Code Playgroud)

或者,将其编写如下:

class Item:
    def __init__(self, string=''):
        self.string = string
    from_string = classmethod(f)
    def f(string):
        return Item(string)
Run Code Online (Sandbox Code Playgroud)

基本上,我想更多地了解装饰器,以及如何在其正常上下文之外使用它们(以了解其幕后工作)。

python decorator class-method python-3.x

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

Python 类多态性

我正在练习多态,以下代码返回错误

class Animal:
    def talk(self, something):
        print(something)

class Dog(Animal):
    def talk(self):
        super().talk("woof woof")

Bonny = Dog
Bonny.talk()
Run Code Online (Sandbox Code Playgroud)
TypeError: talk() missing 1 required positional argument: 'self'
Run Code Online (Sandbox Code Playgroud)

根据我学到的,邦尼应该是自我论证,所以为什么自我缺失?

python polymorphism class-method

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

Mixin Enums 并检查 Enum 对象是否是该类的子集之一

我有一个 mixin str+Enum 类,它允许我的代码的其他部分访问我的变量状态的字符串表示。

有一个特定的 Enumcitrus类型可以来自所有可能枚举的子集。目前我正在使用 aclassmethod来检查“柑橘性”,例如:

from enum import Enum

class Fruits(str, Enum):
    apple = "apple"
    banana = "banana"
    orange = "orange"
    lemon = "lemon"

    citrus = {orange, lemon}

    @classmethod
    def is_citrus(cls, state):
        return state in cls.citrus
Run Code Online (Sandbox Code Playgroud)

[用法]:

>>> o = Fruits.orange
>>> Fruits.is_citrus(o)
True
Run Code Online (Sandbox Code Playgroud)

我的问题是:

  • 那里的类​​方法合适吗?
  • 有没有更好的方法来改善“柑橘性”的检查方式?
  • 目前,我将不得不使用这些Fruits.is_citrus方法来检查oEnum 对象,如何Fruit更改该类以便我可以执行类似的操作o.is_citrus()

python enums class class-method

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

方法创建错误

我正在尝试为我的程序创建一个方法,当被调用时,会要求您按Enter继续.但是,BlueJ给了我一条错误信息,说"预期".以下是我的代码

注意:continue类还没有完全完成.


import java.util.Scanner;

public class BlackjackRunner

{

   public static void main (String[]args)

   {

       System.out.print("Ready to play Blackjack(y/n)? =====> ");
       Scanner input = new Scanner(System.in);
       String response = input.nextLine();
       System.out.println();
       if(response.charAt(0) != 'y' || response.charAt(0)!= 'Y')
            System.out.println("Too bad, you play");
       else
            System.out.println("Good.");  


   }

   public static void*** continue()

   {

       System.out.println("-----PRESS ENTER TO CONTINUE-----");
       Scanner wait = new Scanner(System.in);

   }

}
Run Code Online (Sandbox Code Playgroud)

BlueJ在void语句之后给出了一条错误消息(其中***).我不确定为什么这是不正确的.如果有人可以解释/帮助,那将是美好的.

java static-methods void class-method

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

equals() 和 hashCode() 可以是 lambda 表达式吗?

我是 Java 新手。有人可以向我解释一下这里使用 lambda 和方法有什么区别吗?

方法等于()

  @Override
  public boolean equals(Object o) {

    if (this == o) {
      return true;
    }
    if (!(o instanceof Book)) {
      return false;
    }

    Book book = (Book) o;

    if (!author.equals(book.author)) {
      return false;
    }
    return title.equals(book.title);
  }
Run Code Online (Sandbox Code Playgroud)

拉姆达等于()

  public Function<Object, Boolean> equals = (Object o) -> {
    if (this == o) {
      return true;
    }
    if (!(o instanceof Book)) {
      return false;
    }

    Book book = (Book) o;

    if (!author.equals(book.author)) {
      return false;
    }
    return …
Run Code Online (Sandbox Code Playgroud)

java lambda equals hashcode class-method

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