标签: class-method

Python类方法在类外

我必须使用一些 Python 库,其中包含具有各种实用程序的文件:类和方法。其中一种方法是按以下方式定义的(我无法放置完整代码):

@classmethod
def do_something(cls, args=None, **kwargs):
Run Code Online (Sandbox Code Playgroud)

但这个声明是在任何类之外的。我怎样才能访问这个方法?调用 bydo_something(myClass)会出现错误:TypeError: 'classmethod' object is not callable。在类之外创建类方法的目的是什么?

python class-method

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

在python中覆盖@classmethods的__str__方法

我试图覆盖__str____repr__类,如下面的代码所示。每当我调用 instance_method 时都会调用新方法,但对 class_method 的对象调用保持不变(请参阅下面的代码片段和输出,以便于了解)。有没有办法可以覆盖__str__and __repr__for@classmethod以便cls可以更改的值?

我也尝试添加__str____repr__as@classmethod但没有任何改变。

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

    def __str__(self):
        return f"Added {self.name}"

    def __repr__(self):
        return f"instance method repr"

    def instance_method(self):
        print(f"instance method {self}")

    @classmethod
    def __repr__(cls):
        return f"class method"

    @classmethod
    def __str__(cls):
        return f"class method"

    @classmethod
    def class_method(cls):
        print(f"class method '{cls}'")

    @staticmethod
    def static_method():
        print(f"static method")

    def add(self, a: int,b: int,c: int) -> int:
        return …
Run Code Online (Sandbox Code Playgroud)

python oop methods class class-method

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

从类方法访问属性?

为了使我的代码可测试,我创建了一个惰性初始化器; 这样在我的单元测试中,我可以在调用getter之前模拟我想要的任何对象.

但是,对于类方法,我的类方法无法访问我定义的属性.

  1. 有没有办法让我的类方法可以访问属性?
  2. 如果没有,有没有办法创建也可以在这个类之外访问的静态变量,即可以通过我的单元测试类访问?

@implementation
@synthesize webService;

+ (void)doSomething
{
   self.webService.url = @"some url";
   [self.webService start];
   // do other things
}

- (WebService*)webService
{
   if (!webService)
   {
      webService = [[WebService alloc] init];
   }
   return webService;
}

@end
Run Code Online (Sandbox Code Playgroud)

objective-c static-variables class-method

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

Mutating方法发送到不可变对象

我正在使用JSONKit来解析我的iPhone应用程序中从我的服务器返回的JSON字符串.服务器响应的一部分是一些Base64编码的图像,我想将其解码为实际图像并添加到解析器创建的对象中.问题是我似乎无法弄清楚解析器返回什么类的类,因此可以使用哪种方法与对象进行交互.我在JSONKit文档中搜索了我的问题的答案,但还没有找到它.

decodedData = [[request responseString] objectFromJSONString];

int i = 0;
[Base64 initialize];
for (NSString *base64String in [decodedData valueForKey:@"base64String"]) {
    UIImage *image = [UIImage imageWithData:[Base64 decode:base64String]];
    [decodedData setValue:image forKey:@"image"];
    i++;
}
Run Code Online (Sandbox Code Playgroud)

此代码放在一个方法中,该方法在请求成功完成并在[request responseString](JSON)中返回响应时被调用.该decodedData对象的类是在头文件中定义.不管是什么,我宣布它作为(或者NSArray,NSMutableArray,NSDictionary,或NSMutableDictionary)我得到的代码时运行(它编译就好了),这是相同的错误:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '*** -[JKDictionary setObject:forKey:]: mutating method sent to immutable object'
Run Code Online (Sandbox Code Playgroud)

任何人都能告诉我这个类是什么类,以及我应该怎么做才能将Base64解码后的图像添加到对象中?

我对Objective-C很新,所以请耐心等待.谢谢.

parsing json class-method ios

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

Objective-C类方法不会在实例方法的情况下调用委托方法

我有以下两种方法:

-(void)authenticateUserToGoogle:(NSString *)userName withPassword:(NSString *)password {


    NSString *URLstr = GOOGLE_CLIENT_LOGIN;
    URLstr = @"http://www.google.com/ig/api?stock=AAPL";
    NSURL *theURL = [NSURL URLWithString:URLstr];
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:theURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100.0];

    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

    if (!theConnection) {
        NSLog(@"COuldn't register device information with Parking Server");
    } else {
        NSLog(@"Got a connection!!");
        NSMutableData       *_responseData = [NSMutableData data];
        NSLog(@"respone_data = %@",_responseData);

    }
    }

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response;
    NSInteger statusCode = [HTTPResponse statusCode];

    if (404 == statusCode || 500 == …
Run Code Online (Sandbox Code Playgroud)

delegates objective-c nsurlconnection class-method instance-method

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

为什么在调用自己的类方法时需要使用[self class]?

我在这里阅读了一个主题 http://www.mikeash.com/pyblog/friday-qa-2010-05-14-what-every-apple-programmer-should-know.html.迈克说"在调用你自己的类方法时总是使用[self class]".但我不明白为什么.你能给我举个例子吗 ?

objective-c self class-method

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

Ruby:选择性类继承?

所以,我一直在玩一些模型,我遇到了一种情况,我真的想通过子类来限制类方法的继承.麻烦的是,我的实验到目前为止证实了我的理解,这是不可能做到的.

我天真地尝试了以下方法:

class Policy
  class << self
    def lookup(object)
      #returns a subclass by analyzing the given object, following a naming convention
    end

    def inherited( sub )
      sub.class_eval { remove_method :lookup }
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

当然这不起作用,因为子类没有方法,它在超类上.之后我尝试了:

def inherited( sub )
  class << Policy
    remove_method :lookup
  end
end
Run Code Online (Sandbox Code Playgroud)

这就像一个魅力,哈哈,除了它的工作的微小细节,通过在第一次加载子类时从超类中取出该方法.哎呀!

所以,由于Ruby查找方法的方式,我很确定这不起作用.

我感兴趣的原因是,在我正在处理的行为中,根据命名约定,您可以有许多不同的策略,并且我希望有一个很好的干净方法来获取对任何其他类的策略的引用对象.对我来说,在语法上,这样做似乎很好:

class RecordPolicy < Policy
  # sets policy concerning records,
  # inherits common policy behavior from Policy
end

class Record
end

$> record = Record.new
=> #<Record:0x0000>
$> Policy.lookup(record)
=> RecordPolicy
Run Code Online (Sandbox Code Playgroud)

但是,我认为能够打电话没有任何意义 …

ruby inheritance class-method

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

如何在类方法目标C中访问self

我有一个使用类方法的Utility类.我试图在类方法中引用self但不能.我想知道如何在类方法中声明以下内容:

[MRProgressOverlayView showOverlayAddedTo:self.window animated:YES];
Run Code Online (Sandbox Code Playgroud)

self.window 它说会员参考类型 struct objc_class *' is a pointer; maybe you meant to use '->'

与无法调用有关的另一个问题self是我如何@property在我.h的类方法中引用我声明的声明 .m.

这是我的类方法:

.m
+ (void)showHUD
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
    [MRProgressOverlayView showOverlayAddedTo:self.window animated:YES];

    //I would preferably like to call my property here instead
}


.h
@property (nonatomic) MRProgress * mrProgress;
Run Code Online (Sandbox Code Playgroud)

objective-c class-method ios

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

python 3中类级别的__enter__和__exit__

我没有成功尝试获取magic with-statement方法__enter____exit__在类级别上运行:

class Spam():

    @classmethod
    def __enter__(cls):
        return cls

    @classmethod
    def __exit__(cls, typ, value, tb):
        cls.cleanup_stuff()


with Spam:
    pass
Run Code Online (Sandbox Code Playgroud)

但是,这将导致AttributeError:

Traceback (most recent call last):
  File "./test.py", line 15, in <module>
    with Spam:
AttributeError: __exit__
Run Code Online (Sandbox Code Playgroud)

是否可以在类级别使用__enter____exit__方法?

python with-statement class-method python-3.x

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

如何在React组件上测试定义为箭头函数(类属性)的组件方法?

我可以通过使用间谍来测试类方法Component.prototype.但是,我的许多类方法都是类属性,因为我需要使用this(for this.setState等),因为构造函数中的绑定非常繁琐且看起来很丑,所以在我看来使用箭头函数要好得多.我使用类属性构建的组件在浏览器中工作,所以我知道我的babel配置是正确的.以下是我要测试的组件:

    //Chat.js
    import React from 'react';
    import { connect } from 'react-redux';

    import { fetchThreadById, passMessageToRedux } from '../actions/social';
    import withLogin from './hoc/withLogin';
    import withTargetUser from './hoc/withTargetUser';
    import withSocket from './hoc/withSocket';
    import ChatMessagesList from './ChatMessagesList';
    import ChatForm from './ChatForm';

    export class Chat extends React.Component {
        state = {
            messages : [],
        };
        componentDidMount() {
            const { auth, targetUser, fetchThreadById, passMessageToRedux } = this.props;
            const threadId = this.sortIds(auth._id, targetUser._id);
            //Using the exact same naming scheme …
Run Code Online (Sandbox Code Playgroud)

javascript class-method reactjs jestjs enzyme

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