我想知道人们如何决定是否将方法定义为静态方法.我知道如果一个方法不需要访问实例字段,那么它只能被定义为静态.因此,假设我们有一个不访问实例字段的方法,您是否始终将此方法定义为静态,或者仅在您需要静态调用它时(不引用实例).
也许另一种问同一个问题的方法是你使用静态还是非静态作为默认值?
我正在尝试编写一个python类,它使用需要实例状态信息的装饰器函数.这是按预期工作,但如果我明确地使装饰器成为静态调试,我会收到以下错误:
Traceback (most recent call last):
File "tford.py", line 1, in <module>
class TFord(object):
File "tford.py", line 14, in TFord
@ensure_black
TypeError: 'staticmethod' object is not callable
Run Code Online (Sandbox Code Playgroud)
为什么?
这是代码:
class TFord(object):
def __init__(self, color):
self.color = color
@staticmethod
def ensure_black(func):
def _aux(self, *args, **kwargs):
if self.color == 'black':
return func(*args, **kwargs)
else:
return None
return _aux
@ensure_black
def get():
return 'Here is your shiny new T-Ford'
if __name__ == '__main__':
ford_red = TFord('red')
ford_black = TFord('black')
print ford_red.get()
print ford_black.get() …Run Code Online (Sandbox Code Playgroud) 我正在尝试将以下Objective-C代码转换为Swift.在我的Objective-C代码中,有一个静态变量,它可以从类方法访问.
@implementation SomeClass
static NSMutableArray *_items;
+ (void)someMethod {
[_items removeAll];
}
@end
Run Code Online (Sandbox Code Playgroud)
因为你无法private var items = [AnyObject]()从Swift中的类函数访问这样声明的类型,所以我为它创建了一个存储属性.
class var items: [AnyObject] {
return [AnyObject]()
}
Run Code Online (Sandbox Code Playgroud)
而我正试图从类函数中调用一个方法.
class func someFunction() {
items.removeAll(keepCapacity: false)
}
Run Code Online (Sandbox Code Playgroud)
但我得到这个错误类型'[AnyObject]'的不可变值只有名为'removeAll'的变异成员.
任何人都可以告诉我这个错误的原因是什么以及如何纠正它?
谢谢.
我一直在寻找的请求剖析从升压:: ASIO例子,我想知道为什么私有成员函数一样is_char()的static?:
class request_parser
{
...
private:
static bool is_char(int c);
...
};
Run Code Online (Sandbox Code Playgroud)
它用在函数消耗中,它不是静态函数:
boost::tribool request_parser::consume(request& req, char input)
{
switch (state_)
{
case method_start:
if (!is_char(input) || is_ctl(input) || is_tspecial(input))
{
return false;
}
...
Run Code Online (Sandbox Code Playgroud)
只有成员函数可以调用,is_char()并且没有静态成员函数正在调用is_char().那么为什么这些函数是静态的呢?
super()是不是要用于staticmethods?
当我尝试类似的东西
class First(object):
@staticmethod
def getlist():
return ['first']
class Second(First):
@staticmethod
def getlist():
l = super(Second).getlist()
l.append('second')
return l
a = Second.getlist()
print a
Run Code Online (Sandbox Code Playgroud)
我收到以下错误
Traceback (most recent call last):
File "asdf.py", line 13, in <module>
a = Second.getlist()
File "asdf.py", line 9, in getlist
l = super(Second).getlist()
AttributeError: 'super' object has no attribute 'getlist'
Run Code Online (Sandbox Code Playgroud)
如果我将staticmethods更改为classmethods并将类实例传递给super(),那么一切正常.我在这里不正确地调用超级(类型)还是有些东西我不见了?
我有一个类,让我们说CAppPath有一个静态方法:
public:
static CString GetAppPath();
Run Code Online (Sandbox Code Playgroud)
并在CAppPath.cpp其中定义为:
CString CAppPath::GetAppPath()
{
return "C:\..\MypAth";
}
Run Code Online (Sandbox Code Playgroud)
现在我有另一个班CXMLHandler,我已经加入CAppPath.h了.但是我如何调用该GetAppPath()方法?我试过了:
#include "CAppPath.h"
void CXMLHandler::MyMethod
{
CNDSClientDlg->GetAppPath();
}
Run Code Online (Sandbox Code Playgroud)
但它不起作用.我应该如何访问此方法?由于它是一个静态方法,我是否需要创建该类的对象,还是应该使该类本身是静态的?
我使用以下内容.
Powermock-mockito 1.5.12
Mockito 1.95
junit 4.11
Run Code Online (Sandbox Code Playgroud)
这是我的utils类
public void InternalUtils {
public static void sendEmail(String from, String[] to, String msg, String body) {
}
}
Run Code Online (Sandbox Code Playgroud)
这是被测试班级的要点:
public class InternalService {
public void processOrder(Order order) {
if (order.isSuccessful()) {
InternalUtils.sendEmail(...);
}
}
}
Run Code Online (Sandbox Code Playgroud)
以下是测试:
@PrepareForTest({InternalUtils.class})
@RunWith(PowerMockRunner.class)
public class InternalService {
public void verifyEmailSend() {
mockStatic(Internalutils.class);
doNothing().when(InternalUtils, "sendEmail", anyString(), any(String.class), anyString(), anyString());
Order order = mock(Order.class);
when(order.isSuccessful()).thenReturn(true);
InternalService is = new InternalService();
verifyStatic(times(1));
is.processOrder(order);
}
}
Run Code Online (Sandbox Code Playgroud)
上述测试失败.给出的验证模式为none,但根据代码,如果订单成功,则必须发送电子邮件.
C++语法允许在struct/class中定义重载运算符,如:
struct X
{
void operator+(X);
}
Run Code Online (Sandbox Code Playgroud)
或者在struct/class之外,如:
void operator+(X, X);
Run Code Online (Sandbox Code Playgroud)
但不是
struct X
{
static void operator+(X, X);
}
Run Code Online (Sandbox Code Playgroud)
有没有人知道这个决定的理由?为什么不允许第三种形式?(MSVC给出语法错误).也许这背后有一些故事?
ps同时存在第一个和第二个定义会产生歧义:
1>CppTest1.cxx
1>c:\ballerup\misc\cf_html\cpptest1.cxx(39) : error C2593: 'operator +' is ambiguous
1> c:\ballerup\misc\cf_html\cpptest1.cxx(13): could be 'void B1::operator +(B1 &)'
1> c:\ballerup\misc\cf_html\cpptest1.cxx(16): or 'void operator +(B1 &,B1 &)'
1> while trying to match the argument list '(B1, B1)'
Run Code Online (Sandbox Code Playgroud)
我不明白为什么这种模糊性比1,3或2,3更好.
我继承了一个项目,其中包含许多大类,只有类对象(整数,字符串等).我希望能够检查属性是否存在而无需手动定义属性列表.
是否可以使用标准语法使python 类本身可迭代?也就是说,我希望能够使用for attr in Foo:(或甚至)迭代所有类的属性,if attr in Foo而无需首先创建类的实例.我想我可以通过定义来做到这一点__iter__,但到目前为止我还没有完全掌握我正在寻找的东西.
我通过添加如下__iter__方法实现了我想要的一些:
class Foo:
bar = "bar"
baz = 1
@staticmethod
def __iter__():
return iter([attr for attr in dir(Foo) if attr[:2] != "__"])
Run Code Online (Sandbox Code Playgroud)
但是,这并不能完全满足我的需求:
Run Code Online (Sandbox Code Playgroud)>>> for x in Foo: ... print(x) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'classobj' object is not iterable
即便如此,这仍然有效:
Run Code Online (Sandbox Code Playgroud)>>> for x in Foo.__iter__(): ... print(x) bar baz
static-methods ×10
c++ ×3
python ×3
oop ×2
attributes ×1
c# ×1
class ×1
decorator ×1
ios ×1
java ×1
loops ×1
mfc ×1
mockito ×1
performance ×1
python-2.7 ×1
super ×1
swift ×1
syntax ×1
unit-testing ×1
windows ×1