标签: class-method

在类中使用self方法

我在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-design objective-c class-method objc-protocol

9
推荐指数
1
解决办法
5419
查看次数

为什么classmethod的超级需要第二个参数?

这按预期工作:

>>> 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)

python inheritance python-2.x class-method python-3.x

9
推荐指数
1
解决办法
977
查看次数

访问目标c中的类方法.使用自我或类名?

我正在学习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)

compiler-errors objective-c class-method ios

9
推荐指数
1
解决办法
9343
查看次数

Objective C - 在主线程上调用类方法?

我如何CLASS METHOD在主线程上调用?就像是:

[SomeClass performSelectorOnMainThread:staticMethod withObject:nil];
Run Code Online (Sandbox Code Playgroud)

请不要告诉我创建一个常规方法来调用这个类方法.这将是一个明显的解决方案,但不是很干净.

谢谢

iphone objective-c thread-safety class-method

8
推荐指数
1
解决办法
6246
查看次数

如何从ARC下的运行时定义的类方法返回结构值?

我有一个返回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

8
推荐指数
2
解决办法
6410
查看次数

在创建Python类时调用类方法

我想在类创建时自动运行一些可以调用其他类方法的代码.我没有在类声明本身中找到这样做的方法,并最终创建一个@classmethod被调用__clsinit__并在类声明后立即从定义范围调用它.是否有一个我可以定义的方法,以便在创建类对象后自动调用它?

python initializer class-method

8
推荐指数
1
解决办法
2784
查看次数

目标C中的静态方法(不是类方法)

在阅读这个问题并接受问题的答案时,我无法区分这两种方法.实际上通过阅读示例得到了重点,但后来,我无法编写自己的静态方法.

我尝试在目标c静态方法中使用googling 创建静态方法

这让我回到了这个这个问题的链接.但是,这里的例子是CLASS方法,根据问题的第一个链接.这让我感到困惑.

这里的任何人都可以告诉我如何创建一个不是类方法静态方法

任何关于此的亮点都将受到赞赏.

static-methods objective-c class-method

8
推荐指数
1
解决办法
8389
查看次数

复制自定义对象时出现深层复制失败

我有一个类将字典转换为这样的对象

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 class class-method python-2.7

8
推荐指数
1
解决办法
2549
查看次数

为什么在没有“self”且没有装饰器的情况下声明 Python 类的方法不会引发异常?

我认为以下代码会导致错误,因为据我所知,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 装饰器的情况下得到一个看似有效的静态方法?”

python methods static-methods class class-method

8
推荐指数
2
解决办法
6238
查看次数

具有自我类型的通用协议中的类方法,mypy类型检查失败

一点背景,我基本上需要定义一个int包装类型,比如说MyInt(在其他一些类中),以及另一个Interval可以接受MyInt对象以及其他类型对象的泛型类型.由于不可接受的类型Interval不属于整洁的层次结构,我认为这将是实验的完美用例Protocol,在我的情况下需要几个方法和几个@classmethods.所有方法都返回一个"自我类型",即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)

python class-method structural-typing python-3.x mypy

8
推荐指数
1
解决办法
608
查看次数