标签: class-method

Python类方法 - 有没有办法缩短调用次数?

我正在玩Python,我在一个不同的包中创建了一个类来调用它.在这个类中,我添加了一个从我的main函数调用的类方法.同样,它们位于不同的包中.调用类方法的行比我在其他地方看到的示例要长得多.这些示例倾向于从同一个包中调用类方法 - 从而缩短了调用语法.

这是一个我希望有帮助的例子:

在'config'包中:

class TestClass :
   memberdict = { }

   @classmethod
   def add_key( clazz, key, value ) :
      memberdict[ key ] = value
Run Code Online (Sandbox Code Playgroud)

现在在一个名为'test'的不同包中:

import sys
import config.TestClass

def main() :
   config.TestClass.TestClass.add_key( "mykey", "newvalue" )
   return 0

if __name__ == "__main__" :
    sys.exit( main() )
Run Code Online (Sandbox Code Playgroud)

您可以看到'config.TestClass.TestClass.add_key'如何比普通的类方法调用更冗长.有没有办法缩短它?也许'TestClass.add_key'?我是否以一种奇怪的方式定义了一些东西(与python文件名匹配的类的情况?)

python class-method

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

创建可以看到当前类方法的装饰器

你能在类中创建一个装饰器来查看类方法和变量吗?

这里的装饰者没有看到:self.longcondition()

class Foo:
    def __init__(self, name):
        self.name = name

    # decorator that will see the self.longcondition ???
    class canRun(object):
            def __init__(self, f):
                self.f = f

            def __call__(self, *args):
                if self.longcondition(): # <-------- ???
                    self.f(*args)

    # this is supposed to be a very long condition :)
    def longcondition(self):
        return isinstance(self.name, str)

    @canRun # <------
    def run(self, times):
        for i in xrange(times):
            print "%s. run... %s" % (i, self.name)
Run Code Online (Sandbox Code Playgroud)

python decorator class-method

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

如何包装(猴子补丁)@classmethod

我想修补一个单一的类方法,保持旧的功能.考虑一下我的代码来获取想法.这是我的代码(非常合成的例子).

#!/usr/bin/env python

class A:

  @classmethod
  def foo(kls, param):
    print 'A.foo called, param is ' + param

  def bar(self, param):
    print 'A.bar called, param is ' + param


a = A()
a.foo('param_foo')
a.bar('param_bar')

# Patching things

def bar_wrapper(wrapped_func):
  def _w(*args, **kwargs):
    print '<bar_wrap>'
    wrapped_func(*args, **kwargs)
    print '</bar_wrap>'
  return _w

def foo_wrapper(wrapped_func):
  # Something missing here?
  def _w(*args, **kwargs):
    print '<foo_wrap>'
    wrapped_func(*args, **kwargs)
    print '</foo_wrap>'
  return _w

# Everything is pretty ok
A.bar = bar_wrapper(A.bar)
a.bar('is_is_wrapped?')

# Failed to wrap @classmethod …
Run Code Online (Sandbox Code Playgroud)

python monkeypatching decorator class-method python-decorators

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

命名方法的简单规则,与ARC命名约定兼容

我很难理解ARC的命名约定.我一直用ARC编码,我猜这就是原因.

1.类方法

  • 我应该为以下方法选择什么名称?
  • 这两个名字之间在内存管理上有什么不同?

这个名字:

+ (MyObject *)newObjectFrom:(MyObject *)anObject 
                withOptions:(NSDictionary*)options
{
    MyObject * newObject = [anObject copy] ;
    [newObject modifyWith:options] ;
    return newObject ;
}
Run Code Online (Sandbox Code Playgroud)

还是这个名字?

+ (MyObject *)objectFrom:(MyObject *)anObject
             withOptions:(NSDictionary*)options
{
    MyObject * newObject = [anObject copy] ;
    [newObject modifyWith:options] ;
    return newObject ;
}
Run Code Online (Sandbox Code Playgroud)

2.实例方法

  • 我应该为以下方法选择什么名称?
  • 这两个名字之间在内存管理上有什么不同?

这个名字:

- (MyObject *)newObjectwithOptions:(NSDictionary*)options
{
    MyObject * newObject = [self copy] ;
    [newObject modifyWith:options] ;
    return newObject ;
}
Run Code Online (Sandbox Code Playgroud)

还是这个名字?

- (MyObject *)objectwithOptions:(NSDictionary*)options
{
    MyObject * newObject = [self copy] ; …
Run Code Online (Sandbox Code Playgroud)

memory-leaks objective-c naming-conventions class-method automatic-ref-counting

4
推荐指数
3
解决办法
1564
查看次数

在UML中表示类变量和方法

许多编程语言允许您定义类/实例方法,并且属性也相同.例如Python,Smalltalk.我有这些概念.例如,对于变量,每个对象都有自己的变量副本.类变量只有一个与该类的所有实例共享的变量副本.

我的疑问是:如何在UML中表示类方法和类属性?我想通过静态表示它,就像在C++,Java和C#中一样,但它可以吗?UML中的"static"和"class"是一样的吗?

谢谢!

uml class-diagram class-method class-variables

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

python classmethods不能从类中调用.__ dict__

我正在学习classmethodspython 的概念.

class A():
    n=0
    # object method
    def func_o(self):
        self.n += 1
        print self.n

    # well, class method
    @classmethod
    def func_c(cls):
        cls.n += 1
        print cls.n
Run Code Online (Sandbox Code Playgroud)

在检查callable()类的属性时,我遇到了这个特殊的输出:

>>> [(k, callable(v)) for k,v in A.__dict__.items()]
[('__module__', False), ('__doc__', False), ('func_o', True), ('func_c', False), ('n', False)] 
Run Code Online (Sandbox Code Playgroud)

('func_o', True)即使班级__dict__被检查,同样('func_c', False)由于某种原因.

谁能解释一下?

python oop class-method python-2.7

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

cls在装饰类的继承classmethod中的行为

我正在尝试使用调用它们时使用的参数之一对类的类方法进行一些验证.

为此,我正在使用类的装饰器将装饰器应用于所需的方法,该方法将使用函数中的一个参数执行验证功能.

这一切都适用于基类(对于这个例子,我将称之为Parent).

但是,如果我创建另一个继承的类Parent(对于此示例我将调用它Child),继承的装饰classmethod不再正常运行.

cls的classmethod中的参数Child不是Child预期的,而是Parent相反的.

以下面的例子为例

import inspect


def is_number(word):
    if word.isdigit():
        print('Validation passed')
    else:
        raise Exception('Validation failed')


class ClassDecorator(object):

    def __init__(self, *args):
        self.validators = args

    def __decorateMethod(self):
        def wrapped(method):
            def wrapper(cls, word, *args, **kwargs):
                for validator in self.validators:
                    validator(word)
                return method(word, *args, **kwargs)
            return wrapper
        return wrapped

    def __call__(self, cls):
        for name, method in inspect.getmembers(cls):
            if name == 'shout':
                decoratedMethod = self.__decorateMethod()(method)
                setattr(cls, name, classmethod(decoratedMethod)) …
Run Code Online (Sandbox Code Playgroud)

python inheritance class-method python-decorators

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

将类方法访问实例方法的最佳方法

class Test(object):

    def __init__(self):
        pass

    def testmethod(self):
        # instance method
        self.task(10)      # type-1 access class method

        cls = self.__class__ 
        cls.task(20)        # type-2 access class method 

    @classmethod 
    def task(cls,val)
        print(val)
Run Code Online (Sandbox Code Playgroud)

我有两种方法可以将类方法访问实例方法。

self.task(10)
Run Code Online (Sandbox Code Playgroud)

要么

cls = self.__class__
cls.task(20)
Run Code Online (Sandbox Code Playgroud)

我的问题是哪一个最好,为什么?

如果两种方法都不相同,那么我在哪种条件下使用哪种方法?

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

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

Calling python class method which has no argument

I am new to python (coming from the c++ world) and was experimenting with class methods. I created a method without any argument (purposefully avoided self argument in this case). Then I tried to call it

class car:

    def car_method():
        print("Inside Car method")


obj = car_method()
obj.car_method()    <---- this creates error: TypeError: car_method() takes 0 positional arguments but 1 was given
Run Code Online (Sandbox Code Playgroud)

I think this error is because, In Python, every class method, when called is always passed at least one …

python self parameter-passing class-method python-3.x

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

@classmethod没有调用我的自定义描述符的__get__

我有一个装饰器Special,它将一个函数本身转换为两个版本:一个可以直接调用并以结果为前缀'regular ';一个可以使用.special并以结果为前缀'special '

class Special:
    def __init__(self, func):
        self.func = func

    def __get__(self, instance, owner=None):
        if instance is None:
            return self
        return Special(self.func.__get__(instance, owner))

    def special(self, *args, **kwargs):
        return 'special ' + self.func(*args, **kwargs)

    def __call__(self, *args, **kwargs):
        return 'regular ' + self.func(*args, **kwargs)
Run Code Online (Sandbox Code Playgroud)

它适用于常规方法和静态方法-但.special不适用于类方法:

class Foo:
    @Special
    def bar(self):
        return 'bar'

    @staticmethod
    @Special
    def baz():
        return 'baz'

    @classmethod
    @Special
    def qux(cls):
        return 'qux'

assert Foo().bar() == 'regular bar'
assert …
Run Code Online (Sandbox Code Playgroud)

python class-method python-decorators

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