我必须使用一些 Python 库,其中包含具有各种实用程序的文件:类和方法。其中一种方法是按以下方式定义的(我无法放置完整代码):
@classmethod
def do_something(cls, args=None, **kwargs):
Run Code Online (Sandbox Code Playgroud)
但这个声明是在任何类之外的。我怎样才能访问这个方法?调用 bydo_something(myClass)会出现错误:TypeError: 'classmethod' object is not callable。在类之外创建类方法的目的是什么?
我试图覆盖__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) 为了使我的代码可测试,我创建了一个惰性初始化器; 这样在我的单元测试中,我可以在调用getter之前模拟我想要的任何对象.
但是,对于类方法,我的类方法无法访问我定义的属性.
@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) 我正在使用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很新,所以请耐心等待.谢谢.
我有以下两种方法:
-(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
我在这里阅读了一个主题 http://www.mikeash.com/pyblog/friday-qa-2010-05-14-what-every-apple-programmer-should-know.html.迈克说"在调用你自己的类方法时总是使用[self class]".但我不明白为什么.你能给我举个例子吗 ?
所以,我一直在玩一些模型,我遇到了一种情况,我真的想通过子类来限制类方法的继承.麻烦的是,我的实验到目前为止证实了我的理解,这是不可能做到的.
我天真地尝试了以下方法:
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)
但是,我认为能够打电话没有任何意义 …
我有一个使用类方法的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) 我没有成功尝试获取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__方法?
我可以通过使用间谍来测试类方法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) class-method ×10
objective-c ×4
python ×3
ios ×2
class ×1
delegates ×1
enzyme ×1
inheritance ×1
javascript ×1
jestjs ×1
json ×1
methods ×1
oop ×1
parsing ×1
python-3.x ×1
reactjs ×1
ruby ×1
self ×1