我在ShareKit中遇到了这个代码,我不明白作者self
在类方法中使用了什么.有一个警告:不兼容的指针类型将'Class'发送到参数类型id<FBSessionDelegate>
. 我想清理这些警告,所以我可以看到那些可能会在以后受到伤害的警告.我能做什么/应该做什么不会打破这个?
这是SHKFacebook.m文件,类名是SHKFacebook
+ (void)logout
{
FBSession *fbSession;
if(!SHKFacebookUseSessionProxy){
fbSession = [FBSession sessionForApplication:SHKFacebookKey
secret:SHKFacebookSecret
delegate:self];
}else {
fbSession = [FBSession sessionForApplication:SHKFacebookKey
getSessionProxy:SHKFacebookSessionProxyURL
delegate:self];
}
[fbSession logout];
}
Run Code Online (Sandbox Code Playgroud) 这按预期工作:
>>> class Foo(object):
... @classmethod
... def hello(cls):
... print 'hello, foo'
...
>>> class Bar(Foo):
... @classmethod
... def hello(cls):
... print 'hello, bar'
... super(Bar, cls).hello()
...
>>> b = Bar()
>>> b.hello()
hello, bar
hello, foo
Run Code Online (Sandbox Code Playgroud)
我也可以显式调用基类:
>>> class Bar(Foo):
... @classmethod
... def hello(cls):
... print 'hello, bar'
... Foo.hello()
...
>>> b = Bar()
>>> b.hello()
hello, bar
hello, foo
Run Code Online (Sandbox Code Playgroud)
我想知道为什么我不能省略第一个参数super
,像这样:
>>> class Bar(Foo):
... @classmethod
... def hello(cls):
... print 'hello, …
Run Code Online (Sandbox Code Playgroud) 我正在学习iOS编程,并且对以下使用关键字self的代码感到困惑.
从我的理解来看,self
就像Java一样this
.它指的是当前实例.当我想调用一个类方法时,通常的方法应该是这样 [PlayingCard validSuits];
但是在一个实例上入侵类方法也没关系,对吧?喜欢[self validSuits];
(我在课堂上所以自我指的是PlayCard的一个实例)
但是在下面的代码中,它在某个地方给出了错误但在别处看起来没问题.(由3条评论指出,这是在Xcode 5.1中)
我错过了什么吗?
(PS我想我是有类似的问题在这里,这是任何一个解答.他甚至得到了使用[游戏牌validSuits]同样的错误.)
// PlayingCard.m
#import "PlayingCard.h"
@implementation PlayingCard
@synthesize suit = _suit;
+ (NSArray *)validSuits {
return @[@"??", @"??", @"??", @"??"];
}
+ (NSArray *)rankStrings {
return @[@"?", @"A", @"2", @"3", @"4",@"5",@"6",@"7",@"8",@"9",@"10",@"J",@"Q",@"K"];
}
+ (NSUInteger)maxRank {
return [[PlayingCard rankStrings] count] -1;
//1. [self rankStrings] works fine.**
}
//override super class's method
- (NSString *)contents {
NSArray *rankStrings = [PlayingCard rankStrings];
//2. if change rankStrings …
Run Code Online (Sandbox Code Playgroud) 我如何CLASS METHOD
在主线程上调用?就像是:
[SomeClass performSelectorOnMainThread:staticMethod withObject:nil];
Run Code Online (Sandbox Code Playgroud)
请不要告诉我创建一个常规方法来调用这个类方法.这将是一个明显的解决方案,但不是很干净.
谢谢
我有一个返回a的类方法CGSize
,我想通过Objective-C运行时函数调用它,因为我将类和方法名称作为字符串值.
我正在使用XCode 4.2中的ARC标志进行编译.
方法签名:
+(CGSize)contentSize:(NSString *)text;
Run Code Online (Sandbox Code Playgroud)
我尝试的第一件事是用objc_msgSend
这样调用它:
Class clazz = NSClassFromString(@"someClassName);
SEL method = NSSelectorFromString(@"contentSize:");
id result = objc_msgSend(clazz, method, text);
Run Code Online (Sandbox Code Playgroud)
这与"EXC_BAD_ACCESS"崩溃并且没有堆栈跟踪.我首先使用了这个,因为文档objc_msgSend
说,
当遇到一个方法调用,编译器生成到的功能之一的呼叫
objc_msgSend
,objc_msgSend_stret
,objc_msgSendSuper
,或objc_msgSendSuper_stret
.[...]使用objc_msgSendSuper_stret
和发送具有数据结构作为返回值的方法objc_msgSend_stret
.
接下来,我用objc_msgSend_stret
这样的:
Class clazz = NSClassFromString(@"someClassName);
SEL method = NSSelectorFromString(@"contentSize:");
CGSize size = CGSizeMake(0, 0);
objc_msgSend_stret(&size, clazz, method, text);
Run Code Online (Sandbox Code Playgroud)
使用上面的签名给出了以下两个编译器错误和两个警告:
错误:自动引用计数问题:ARC不允许将非Objective-C指针类型'CGSize*'(又名'struct CGSize*')隐式转换为'id'
警告:语义问题:不兼容的指针类型将'CGSize*'(又名'struct CGSize*')传递给'id'类型的参数
错误:自动引用计数问题:ARC不允许将Objective-C指针隐式转换为"SEL"
警告:语义问题:不兼容的指针类型将'__unsafe_unretained Class'传递给'SEL'类型的参数
如果我查看方法的声明,它是:
OBJC_EXPORT void objc_msgSend_stret(id self, SEL op, ...)
__OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0);
Run Code Online (Sandbox Code Playgroud)
这与 …
struct objective-c objective-c-runtime class-method automatic-ref-counting
我想在类创建时自动运行一些可以调用其他类方法的代码.我没有在类声明本身中找到这样做的方法,并最终创建一个@classmethod
被调用__clsinit__
并在类声明后立即从定义范围调用它.是否有一个我可以定义的方法,以便在创建类对象后自动调用它?
我有一个类将字典转换为这样的对象
class Dict2obj(dict):
__getattr__= dict.__getitem__
def __init__(self, d):
self.update(**dict((k, self.parse(v))
for k, v in d.iteritems()))
@classmethod
def parse(cls, v):
if isinstance(v, dict):
return cls(v)
elif isinstance(v, list):
return [cls.parse(i) for i in v]
else:
return v
Run Code Online (Sandbox Code Playgroud)
当我尝试制作对象的深层副本时,我收到了此错误
import copy
my_object = Dict2obj(json_data)
copy_object = copy.deepcopy(my_object)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/copy.py", line 172, in deepcopy
copier = getattr(x, "__deepcopy__", None)
KeyError: '__deepcopy__'
Run Code Online (Sandbox Code Playgroud)
但是我在类I中重写getattr函数Dict2obj
能够进行深层复制操作.见下面的例子
class Dict2obj(dict):
__getattr__= dict.__getitem__
def __init__(self, d):
self.update(**dict((k, self.parse(v))
for k, v in d.iteritems()))
def __getattr__(self, key): …
Run Code Online (Sandbox Code Playgroud) 我认为以下代码会导致错误,因为据我所知,Python 类中的方法必须将“self”(或任何其他标签,但按照约定是“self”)作为其第一个参数,或者如果使用了@classmethod
装饰器,则为“cls”或类似名称,如果使用了装饰器,则为 none @staticmethod
。
为什么我在终端中使用 Python 3.5 运行它没有错误,即使test_method
不满足这些要求?它似乎作为静态方法工作正常,但没有装饰器。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
class MyClass:
def test_method(args):
print(args[1])
@staticmethod
def static_method():
print("static_method")
@classmethod
def class_method(cls):
print("class_method")
def main(args):
MyClass.test_method(args)
if __name__ == '__main__':
sys.exit(main(sys.argv))
Run Code Online (Sandbox Code Playgroud)
输出:
$ python3 testscript.py "testing"
$ testing
Run Code Online (Sandbox Code Playgroud)
编辑:
我的问题也可以用不同的措辞,将注意力从self
和转移到@staticmethod
:“我怎么会在没有 @staticmethod 装饰器的情况下得到一个看似有效的静态方法?”
一点背景,我基本上需要定义一个int
包装类型,比如说MyInt
(在其他一些类中),以及另一个Interval
可以接受MyInt
对象以及其他类型对象的泛型类型.由于不可接受的类型Interval
不属于整洁的层次结构,我认为这将是实验的完美用例Protocol
,在我的情况下需要几个方法和几个@classmethod
s.所有方法都返回一个"自我类型",即MyInt.my_method
返回一个MyInt
.这是一个MCVE:
from dataclasses import dataclass
from typing import Union, ClassVar, TypeVar, Generic, Type
from typing_extensions import Protocol
_P = TypeVar('_P', bound='PType')
class PType(Protocol):
@classmethod
def maximum_type_value(cls: Type[_P]) -> _P:
...
@classmethod
def minimum_type_value(cls: Type[_P]) -> _P:
...
def predecessor(self: _P) -> _P:
...
def successor(self: _P) -> _P:
...
@dataclass
class MyInteger:
value: int
_MAX: ClassVar[int] = 42
_MIN: ClassVar[int] = -42 …
Run Code Online (Sandbox Code Playgroud) class-method ×10
objective-c ×5
python ×5
class ×2
python-3.x ×2
class-design ×1
inheritance ×1
initializer ×1
ios ×1
iphone ×1
methods ×1
mypy ×1
python-2.7 ×1
python-2.x ×1
struct ×1