标签: class-method

为什么我不能在类方法中使用python模块current.futures?

我想让我的类方法并行运行,但是它只会产生某种我无法解决的错误。我的代码是:

import concurrent.futures as futures

samples = ['asfd', 'zxcv', 'asf', 'qwer']

class test:
    def __init__(self, samples):
        maturedb = {}
        with futures.ProcessPoolExecutor() as exe:
            for samplename, dResult in exe.map(self.make_readdb, samples):
                maturedb[samplename] = dResult
        print(maturedb)

    def make_readdb(self, samplename):
        return samplename, 1

test(samples)
Run Code Online (Sandbox Code Playgroud)

如果我在Ubuntu计算机上运行此代码,则会发生如下错误:

Traceback (most recent call last):
    File "/usr/lib/python3.2/multiprocessing/queues.py", line 272, in _feedsend(obj)
    _pickle.PicklingError: Can't pickle <class 'method'>: attribute lookup builtins.method failed
Run Code Online (Sandbox Code Playgroud)

方法make_readdb只是简化为一个示例,但是它是实际代码中的瓶颈,我需要使其平行。请帮忙。

python parallel-processing class class-method concurrent.futures

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

使用factory_boy和SQLAlchemy以及类方法

我正在使用SQLAlchemy作为ORM的Pyramid应用程序.我试图用类方法测试模型:

# this is essentially a global used by all the models
Session = scoped_session(sessionmaker(autocommit=False))

class Role(Base):
    __tablename__ = 'role'

    id = sa.Column(sa.types.Integer, primary_key=True)
    name = sa.Column(sa.types.Text, unique=True, nullable=False)

    def __init__(self, **kwargs):
        super(Role, self).__init__(**kwargs)

    @classmethod
    def find_all(self):
        return Session.query(Role).order_by(Role.name).all()
Run Code Online (Sandbox Code Playgroud)

我正在使用factory_boy进行测试,以下是我尝试设置测试工厂的方法:

import factory
from factory.alchemy import SQLAlchemyModelFactory
from sqlalchemy.orm import scoped_session, sessionmaker
from zk.model.meta import Base
from zk.model.role import Role

session = scoped_session(sessionmaker())
engine = create_engine('sqlite://')
session.configure(bind=engine)
Base.metadata.create_all(engine)

class RoleFactory(SQLAlchemyModelFactory):
    FACTORY_FOR = Role
    FACTORY_SESSION = session
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试调用RoleFactory.find_all()测试时,我收到一个错误: …

python sqlalchemy class-method factory-boy

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

Objective-c:如何在类方法中获取Class实例

我有2个类,Parent和Child,Parent有一个名为func的类方法.现在我想在func方法中获取Class实例来区分哪个类是调用者.

@interface Parent : NSObject
+ (void)func;
@end

@implementation Parent

+ (void)func {
    Class *class = howToGetClass();
    NSLog(@"%@ call func", class);
}

@end

@interface Child : Parent
@end

int main() {
    [Child func];    // call func from Child
}
Run Code Online (Sandbox Code Playgroud)

有没有办法在类方法中获取类实例(或类名)?

objective-c class-method

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

如何将起始序列号传递给Django factory_boy工厂?

factory_boy默认1为序列。如何传递数字以用作其他起始号码?我可以对_setup_next_sequence()方法进行子类化,但是如何给它使用一个变量呢?

# File: models.py
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
Run Code Online (Sandbox Code Playgroud)


# File: factories.py
from .models import Book
import factory

class BookFactory(factory.Factory):
  FACTORY_FOR = BookModel  
  title = factory.Sequence(lambda n: u'Title #{}'.format(n))

  @classmethod
  def _setup_next_sequence(cls):      
      # Instead of defaulting to starting with number 1, start with starting_seq_num.
      # But how do I set starting_seq_num?
      return starting_seq_num
Run Code Online (Sandbox Code Playgroud)


# File: make_data.py
from factories import BookFactory

# somehow set starting sequence number here?

BookFactory().create()
Run Code Online (Sandbox Code Playgroud)

我正在使用factory_boy 1.2.0(via pip install …

python django class-method factory-boy

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

ARC语义问题:类没有可见的@interface声明选择器

非常基本的东西,但我无法解决问题所在.在我的项目中,我有一个名为"TheFeedStore"的类,有以下两种方法:

- (BOOL)hasItemBeenRead:(RSSItem *)item
{
   ............
}

- (void)markItemAsRead:(RSSItem *)item
{
  .........
}
Run Code Online (Sandbox Code Playgroud)

我使用以下类方法,以便其他类可以使用它访问这些方法:

+ (TheFeedStore *) sharedStore
{
    static TheFeedStore *feedStore = nil;

    if (!feedStore) {
        feedStore = [[TheFeedStore alloc] init];
    }
    return feedStore;
}
Run Code Online (Sandbox Code Playgroud)

在我的另一个课程中,我可以通过写作轻松访问上述方法

if ([[TheFeedStore sharedStore] hasItemBeenRead:item]) 
Run Code Online (Sandbox Code Playgroud)

要么

[[TheFeedStore sharedStore] markItemAsRead:entry];
Run Code Online (Sandbox Code Playgroud)

但是在另一个类中,如果我尝试以类似的方式访问这些方法,我得到错误"没有可见的@interface为'TheFeedStore'声明了选择器'hasItemBeenRead:"

1)我在类中导入了TheFeedStore.h文件,我正在访问TheFeedStore类的这些方法.

2)我检查了10次,没有拼写错误.

3)我访问的方法也在TheFeedStore.h的头文件中声明

更新:只是为了检查,我已经在TheFeedStore.h中声明了另一个测试方法,同样的结果,一个类可以访问新创建的方法,而其他三个类则不能.

更新:我已经尝试在TheFeedStore.h中创建更多方法,仅用于解决此问题.其他类也无法访问新方法.但是如果这些新方法的返回类型是(RSSChannel*),它是我项目中的另一个模型类,那么它们就变得可访问了.如果它们的返回类型不是某些类,如(void)和(BOOL)那么它们是不可访问的.这是我的TheFeedStore.h https://gist.github.com/jessicamoore112/5558473

iphone xcode objective-c class-method ios

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

收集类变量中的所有实例总是不好的吗?

考虑两个版本的简单天气模型,它存储云的位置:

class cloud:
    def __init__(self, x, y):
        self.x = x
        self.y = y

collection = []
collection.append(cloud(1,2))
collection.append(cloud(4,6))

def update_all_clouds(collection):
    for c in collection:
        cloud.x += 1
        cloud.y += 1

update_all_clouds(collection)
Run Code Online (Sandbox Code Playgroud)

VS

class cloud:
    collection = []
    def __init__(self, x, y)
        self.x = x
        self.y = y
        cloud.collection.append(self)
    @classmethod
    def update_all(cls):
        for c in cloud.collection:
            c.x += 1
            c.y += 1
cloud(1,2)
cloud(4,6)
cloud.update_all()
Run Code Online (Sandbox Code Playgroud)

这基本上受到了惩罚在 类字段中存储类的所有实例是不是很糟糕? 但是这里强调的是对所有实例起作用的类方法.对于第二种方法提供的最后三行的简单性,没有什么可说的吗?

我知道另一种方法是创建一个类似于列表的类,例如,集合并给出类似update_all()的类方法,但对我而言似乎并没有好多了.

python class global-variables class-method class-members

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

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

我来自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
查看次数

如何装饰类或静态方法

我正在编写一个通用类装饰器,它需要将装饰器应用于每个方法。我的第一个方法是这样的:

def class_decorator(cls):
    for name, member in vars(cls).items():
        # Ignore anything that is not a method
        if not isinstance(member, (types.FunctionType, types.BuiltinFunctionType, classmethod, staticmethod)):
            continue

        setattr(cls, name, method_decorator(member))

    return cls
Run Code Online (Sandbox Code Playgroud)

装饰器本身并不是很重要。看起来像这样:

def method_decorator(fn):
    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        # do something
        return fn(*args, **kwargs):

    return wrapper
Run Code Online (Sandbox Code Playgroud)

一旦我测试了它,我遇到了一个问题,这不适用于静态或类方法,并且引发以下错误functools.wraps

AttributeError: 'classmethod' object has no attribute '__module__'
Run Code Online (Sandbox Code Playgroud)

是的,classmethod或者staticmethods不是普通函数,甚至不是可调用函数。一般来说,如果你需要装饰一个classmethod,你首先应用你的装饰器,然后应用classmethod装饰器,但由于这是一个类装饰器,我无法影响装饰器的顺序。

对此有什么好的解决办法吗?

python decorator class-method

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

如何禁止在实例上调用类方法?

我一直在寻找 的源代码peewee,特别Model是该update函数:https://github.com/coleifer/peewee/blob/a33e8ccbd5b1e49f0a781d38d40eb5e8f344eee5/peewee.py#L4718

我不喜欢这样的事实:如果语句未与子句正确耦合,则任何更新操作都会影响模型中的每一行,可以从行实例调用此方法where。因此,我想找到某种方法来禁止从模型实例调用此类方法。

一些谷歌搜索让我相信这可能相当困难。delattr__init__似乎没有工作。从 update 函数运行isclass(self)总是返回 True,因为当我们在类方法内部时,我们实际上类而不是实例。

有什么建议么?

python cpython class-method peewee

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

如何记录从元类继承的方法?

考虑以下元类/类定义:

class Meta(type):
    """A python metaclass."""
    def greet_user(cls):
        """Print a friendly greeting identifying the class's name."""
        print(f"Hello, I'm the class '{cls.__name__}'!")

    
class UsesMeta(metaclass=Meta):
    """A class that uses `Meta` as its metaclass."""
Run Code Online (Sandbox Code Playgroud)

我们知道,在元类中定义一个方法意味着它被类继承,并且可以被类使用。这意味着交互式控制台中的以下代码可以正常工作:

class Meta(type):
    """A python metaclass."""
    def greet_user(cls):
        """Print a friendly greeting identifying the class's name."""
        print(f"Hello, I'm the class '{cls.__name__}'!")

    
class UsesMeta(metaclass=Meta):
    """A class that uses `Meta` as its metaclass."""
Run Code Online (Sandbox Code Playgroud)

然而,这种方法的一个主要缺点是我们可能包含在方法定义中的任何文档都丢失了。如果我们help(UsesMeta)在交互式控制台中键入,我们会看到没有对方法的引用greet_user,更不用说我们在方法定义中放入的文档字符串了:

>>> UsesMeta.greet_user()
Hello, I'm the class 'UsesMeta'!
Run Code Online (Sandbox Code Playgroud)

现在当然,__doc__类的属性是 writable …

python docstring metaclass class-method python-3.x

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