标签: class-method

为什么我的Python类声称我有2个参数而不是1?

#! /usr/bin/env python
import os
import stat
import sys
class chkup:

        def set(file):
                filepermission = os.stat(file)
                user_read()
                user_write()
                user_exec()

        def user_read():
                """Return True if 'file' is readable by user 
            """
            # Extract the permissions bits from the file's (or
            # directory's) stat info.
                b = bool(filepermission.st_mode & stat.S_IRUSR)
                print b
            return b

        def user_write():
                """Return True if 'file' is readable by user 
            """
            # Extract the permissions bits from the file's (or
            # directory's) stat info.
                b = bool(filepermission.st_mode & …
Run Code Online (Sandbox Code Playgroud)

python class-method

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

classmethods的装饰器的一些问题

我有一段代码,我想在其中使用装饰器classmethod,如下所示:

import functools

def mydeco(function):
    @classmethod
    def wrapper(cls):
        return function(cls) 
    return functools.update_wrapper(wrapper, function)
    # return wrapper

class BaseClass(object):
    @classmethod
    @mydeco
    def foo(cls):
        return "42" 

print BaseClass.foo()
Run Code Online (Sandbox Code Playgroud)

当我注释掉@mydeco代码行时,即42打印文本。当包含这个装饰器时,我有几个问题:

如何正确地做到这一点,即,在给定的示例中,原始函数被返回而不被更改。

  • 当使用更复杂的调用return functools.update_wrapper(wrapper, function)来保留一些原始函数时,我得到了错误

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

我不确定这个错误是否与第一个问题有关,但对我来说它看起来是一个不同的问题。欢迎任何解决这些问题的具体建议。

上面的例子并没有真正“做”某事,它只是展示我遇到的问题的最小可能的例子。

python decorator class-method python-2.7

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

如何使用 python-decorator 包来装饰类方法?

我有一个装饰器,我想用它来装饰类方法。在下面的示例中,@mydec 装饰器本身可以正常工作,但是在使用 help() 或 pydoc 时它不会保留函数签名。为了解决这个问题,我查看了使用 @decorator python-decorator 包:

import functools
import decorator


@decorator.decorator
def mydec(func):
    @functools.wraps(func)
    def inner(cls, *args, **kwargs):
        # do some stuff
        return func(cls, *args, **kwargs)
    return inner


class Foo(object):
    @classmethod
    @mydec
    def bar(cls, baz='test', qux=None):
        print (baz, qux)


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

不幸的是,这会导致以下异常:

Traceback (most recent call last):
  File "/tmp/test.py", line 21, in <module>
    Foo.bar()
  File "<string>", line 2, in bar
TypeError: mydec() takes exactly 1 argument (4 given)
Run Code Online (Sandbox Code Playgroud)

python decorator class-method python-decorators

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

如何使用classmethods修改类文档字符串

我的问题:

我创建了一系列节点,每个节点都有一组与之关联的属性对象.使用每个属性的描述和名称初始化属性对象.我希望这些属性及其描述能够在我的sphinx文档中显示,而不必在两个地方维护名称/描述,一次在类的doc字符串中,一次在属性的初始化中.

要说明问题,请考虑以下代码:

class Foo(object):
    """My doc string
    """
    @classmethod
    def default_attributes(cls):
        return {'foo':'description of foo attribute',
                'bar':'description of bar attribute'}

    @classmethod
    def attributes_string(cls):
        attributes = cls.default_attributes()
        result = '\nDefault Attributes:\n'
        for key, value in attributes.iteritems():
            result += '%s: %s\n' % (key, value)
        return result

print Foo.__doc__
Run Code Online (Sandbox Code Playgroud)

我希望Foo.attributes_string的结果显示在Foo的doc字符串中,以便我得到这个:

My doc string

Default Attributes:
foo: description of foo attribute
bar: description of bar attribute
Run Code Online (Sandbox Code Playgroud)

我的解决方案尝试:

首先我想"嘿,这很简单!我只是设置一个类装饰器!":

def my_decorator(cls):
    doc = getattr(cls, '__doc__', '')
    doc += cls.attributes_string()
    cls.__doc__ = doc
    return cls …
Run Code Online (Sandbox Code Playgroud)

python docstring metaclass class-method

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

在Django 1.7中序列化类方法

当我尝试manage.py makemigrations在Django 1.7 上运行时,我收到以下错误:

ValueError: Cannot serialize: <bound method ModelBase.get_default of <class 'printapp.models.JobConfiguration'>>
There are some values Django cannot serialize into migration files.
For more, see https://docs.djangoproject.com/en/dev/topics/migrations/#migration-serializing
Run Code Online (Sandbox Code Playgroud)

所以看起来get_default定义的方法存在问题JobConfiguration,其定义在下面重复:

@classmethod
def get_default(cls):
    result = cls()
    result.save()
    return result
Run Code Online (Sandbox Code Playgroud)

按照错误消息中提供链接,看起来序列化"类引用"是一个受支持的功能.

是一个"类引用"一样@classmethod吗?

如何在"模块的顶级范围"中添加"类引用"?

为什么必须通过迁移跟踪方法?我假设迁移是针对数据库模式的,它只跟踪存储的数据类型,而不是类所使用的方法类型.

值得注意的是:将get_default下面重复的静态方法的定义更改为解决问题,但代价是必须对JobConfiguration类名进行硬编码.

@staticmethod
def get_default():
    result = JobConfiguration()
    result.save()
    return result
Run Code Online (Sandbox Code Playgroud)

(某些上下文:此方法是JobConfiguration.get_default从a中引用的models.OneToOneField(JobConfiguration, default=JobConfiguration.get_default),其效果是为每个创建的字段创建新的JobConfiguration.)

python django django-models class-method django-migrations

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

Swift中的类方法和实例方法有什么区别?

protocol NoteProtocol {
    var body: NSString? { get set }
    var createdAt: NSDate? { get set }
    var entityId: NSString? { get set }
    var modifiedAt: NSDate? { get set }
    var title: NSString? { get set }

    // class methods
    class func insertNewNoteInManagedObjectContext(managedObjectContext: NSManagedObjectContext!) -> NoteProtocol
    class func noteFromNoteEntity(noteEntity: NSManagedObject) -> NoteProtocol

    // instance methods
    func update(#title: String, body: String)
    func deleteInManagedObjectContext(managedObjectContext: NSManagedObjectContext!)
}
Run Code Online (Sandbox Code Playgroud)

嗨这是我在GitHub上找到的一段代码.在这个协议中,类方法和实例方法之间的主要区别是什么?它们是如何定义的?谁能帮我?

oop methods protocols class-method swift

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

Python方法可用于实例化/未实例化的类

我有一个类,它获取细节并使用信息填充类,如果它已经id使用details方法实例化了.如果它没有实例化,我希望它改为使用传入的参数details作为id并返回一个新的实例化对象.类似于以下内容:

f = Foo()
f.id = '123'
f.details()
Run Code Online (Sandbox Code Playgroud)

但也允许:

f = Foo.details(id='123')
Run Code Online (Sandbox Code Playgroud)

我可以使用相同的details方法来完成此任务吗?或者我是否需要创建两个单独的方法并制作一个@classmethod?如果我将一个声明为a @classmethod而另一个不声明,它们可以具有相同的名称吗?

python methods class-method

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

abc.abstractclassmethod:为什么 __isabstractmethod__ 设置为可调用?

Python 3.4 中抽象类方法 abc.py 的实现如下所示:

class abstractclassmethod(classmethod):

    __isabstractmethod__ = True

    def __init__(self, callable):
        callable.__isabstractmethod__ = True
        super().__init__(callable)
Run Code Online (Sandbox Code Playgroud)

Python 2.7 Combine abc.abstractmethod and classmethod的答案就是基于这个实现。

为什么需要在可调用对象上设置 __isabstractmethod__?设置类abstractclassmethod 的类变量__isabstractmethod__ 还不够吗?如果整个 __init__() 定义将被删除(如抽象属性中),哪个用例将不起作用?

abstract-methods class-method python-2.7 python-3.x

5
推荐指数
0
解决办法
966
查看次数

当模板参数名称与内部类名匹配时,为什么编译失败?

以下编译完全正常:

struct MyClass {
  template<typename SameName>
  void foo (SameName* p);
};
struct SameName {};

template<class SameName>
void MyClass::foo (SameName* p) {}
Run Code Online (Sandbox Code Playgroud)

但是,如果我们附上MyClassSameName一些内class Outertemplate外定义的函数,编译失败.

struct Outer {
  /* paste here `MyClass` & `SameName` from above */
};

template<class SameName>
void Outer::MyClass::foo (SameName* p) {}  // <--- error here
//   ^^^^^
Run Code Online (Sandbox Code Playgroud)

克++(03-14)误差是怪异:

error: prototype for ‘void Outer::MyClass::foo(Outer::SameName*)’ does not match any in class ‘Outer::MyClass’
 void Outer::MyClass::foo (SameName* p) {}
      ^~~~~
templateClassMethod.cpp:6:10: error: …
Run Code Online (Sandbox Code Playgroud)

c++ syntax templates compiler-errors class-method

5
推荐指数
0
解决办法
209
查看次数

classmethod在每次访问时返回一个新对象

访问classmethod一个类总是返回一个不同的对象。这与实例或静态方法不同。

class Foo(object):
    @classmethod
    def foo_classmethod(cls):
        pass

    def foo_instancemethod(self):
        pass

    @staticmethod
    def foo_staticmethod():
        pass
Run Code Online (Sandbox Code Playgroud)

当试图比较

In [37]: print(Foo.foo_instancemethod is Foo.foo_instancemethod)
True

In [38]: print(Foo.foo_staticmethod is Foo.foo_staticmethod)
True

In [39]: print(Foo.foo_classmethod is Foo.foo_classmethod)
False
Run Code Online (Sandbox Code Playgroud)

Python 2和3中的行为相同。这看起来像是bug吗?我在酸洗Python3中的类方法并对未酸洗的is对象进行检查时遇到了这个问题。

python pickle class-method python-2.7 python-3.7

5
推荐指数
0
解决办法
55
查看次数