这是一个学术问题,不仅仅是一个实际问题.我正在尝试深入研究Python的基础,我想知道:如果我愿意,我可以在纯Python中实现staticmethod和classmethod装饰器吗?
对于staticmethod也许我可以保持一个参照原有的功能,并调用它省略了第一个参数?
对于classmethod也许我可以保持一个参照原有的功能,并把它传递的第一个参数的类型,而不是争论本身?(我怎么处理它直接在课堂上调用?)
同样,并不是我想在我的程序中实际实现它; 我想学习语言是如何运作的.如果有可能,我会非常感谢代码示例.如果没有,我希望解释为什么理论上无法做到.谢谢!
编辑:感谢您的答案和描述符协议的参考!作为进一步扩展我对Python的理解的一种方法,我想再问两件事:
这可以在没有描述符协议的情况下完成,例如在我们的类中实现__ call __特殊方法吗?
描述符协议在Python 2.7和Python 3.x中的工作方式是否相同?
再次感谢!
2023 年 3 月更新
注意:这是有效的,因为在下一个刻度中,lightDOM 中的N 个(不是全部!)DOM 元素将被解析。
对于 (app.) N > 1000你会遇到麻烦,因为延迟将在解析所有 N 个元素之前结束。
因此,要么添加(大约 20 行)代码来实际检查所有 lightDOM 是否已解析。(但是由于您的 DOM 正在遭受 Obesitas 的困扰,因此您可能还会遇到其他性能问题)
或者只是保持 lightDOM中N 个 DOM 元素的数量较小。
当然,您稍后在解析之后添加的任何 DOM都不会影响任何内容(当不触发时)connectedCallback
2021 年 3 月更新:
FireFox 错误已修复,现在的行为与 Chromium 和 Safari 相同。
这意味着等待 JS EventLoop 为空(带有setTimeout或requestAnimationFrame)现在connectedCallback是一个跨浏览器方法
connectedCallback(){
setTimeout(()=>{
// can access lightDOM here
}); // ,0 not required
}
Run Code Online (Sandbox Code Playgroud)
事件循环到底是什么?- 菲利普·罗伯茨 …
我在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) 在Rails中发送邮件时,通常可以执行以下操作:
UserMailer.password_reset(user).deliver
Run Code Online (Sandbox Code Playgroud)
但如果我们看一下,UserMailer我们可以看到:
def password_reset(user) # not self.password_reset
# ...
end
Run Code Online (Sandbox Code Playgroud)
请注意,方法名称不带前缀self.看一下,看起来你需要首先实例化对象,如下所示.Rails如何做到这一点?
UserMailer.new.password_reset(user).deliver
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) 有时我需要用静态方法编写类,但有可能初始化它并保持状态(对象)
......喜欢:
class A:
@classmethod
def method(cls_or_self):
# get reference to object when A().method() or to class when A.method()
code
Run Code Online (Sandbox Code Playgroud)
我现在拥有的是:
class A:
def method(self = None, *params): code
# or
def method2(self = None, **params): code
# but what I need is rather normal parameters, not optional and named args:
def method3(self_or_cls, a, b=1, c=2, *p, **kw): code
Run Code Online (Sandbox Code Playgroud)
请不要写关于staticmethod和classmethod之间的区别.我感兴趣的是,如果存在这样的装饰器(在或多或少的标准库中),而且如果上面适合于PEP.
在开发源代码项目时,我遇到了以下C函数声明和实现:
// FSNData.h
NSString *stringForMimeType(MimeType type);
@interface FSNData : NSObject
// All the expected objective-c property and instance method declarations
@end
// FSNData.m
#import "FSNData.h"
// where 'type' is an enum
// this does work as expected
NSString *stringForMimeType(MimeType type) {
switch (type) {
case MimeType_image_jpeg: return @"image/jpeg";
case MimeType_image_png: return @"image/png";
default:
NSLog(@"ERROR: FSNData: unknown MimeType: %d", type);
// do not return "application/octet-stream"; instead, let the recipient guess
// http://en.wikipedia.org/wiki/Internet_media_type
return nil;
}
}
@implementation
// all properties and …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) 此脚本失败:
import mock
class MyClass(object):
@classmethod
def my_method(cls):
print('my_method')
def mocked_method(cls):
print('I want this method to get called')
with mock.patch.object(MyClass, 'my_method', mocked_method):
MyClass.my_method()
Run Code Online (Sandbox Code Playgroud)
例外:
Traceback (most recent call last):
File "/home/foo/tmp/test_mocking_classmethod.py", line 14, in <module>
MyClass.my_method()
TypeError: unbound method mocked_method() must be called with MyClass instance as first argument (got nothing instead)
Run Code Online (Sandbox Code Playgroud) 所以 classmethods 可以用作 python 中的替代“构造函数”,它们绑定到类而不是实例,到目前为止很清楚。但我的问题是,如果在类方法的返回实例中必须具有与__init__. 更确切地说:
class MyClass(object):
def __init__(self,name):
self.name=name
@classmethod
def alternative_init(cls,name,surname):
return cls(name,surname)
Run Code Online (Sandbox Code Playgroud)
如果我尝试创建一个实例Myclass("alex")工作正常,但如果我尝试创建一个实例,Myclass.alternative_init("alex","james")我有一个TypeError,因为我传递了许多参数,而 init 只需要 2 。我错过了什么吗?
class-method ×10
python ×5
objective-c ×3
decorator ×2
arguments ×1
c ×1
callback ×1
class-design ×1
constructor ×1
function ×1
inheritance ×1
ios ×1
methods ×1
mocking ×1
oop ×1
python-2.x ×1
python-3.x ×1
ruby ×1
unit-testing ×1