我正在开发Flask扩展,为Flask添加了CouchDB支持.为了使它更容易,我已经子类化,couchdb.mapping.Document因此store和load方法可以使用当前的线程本地数据库.现在,我的代码看起来像这样:
class Document(mapping.Document):
# rest of the methods omitted for brevity
@classmethod
def load(cls, id, db=None):
return mapping.Document.load(cls, db or g.couch, id)
Run Code Online (Sandbox Code Playgroud)
为简洁起见,我遗漏了一些,但那是重要的部分.但是,由于classmethod的工作方式,当我尝试调用此方法时,我收到错误消息
File "flaskext/couchdb.py", line 187, in load
return mapping.Document.load(cls, db or g.couch, id)
TypeError: load() takes exactly 3 arguments (4 given)
Run Code Online (Sandbox Code Playgroud)
我测试了替换呼叫mapping.Document.load.im_func(cls, db or g.couch, id),它有效,但我对访问内部im_属性并不是特别高兴(即使它们已被记录).有没有人有更优雅的方式来处理这个?
我被告知java中的静态方法没有继承,但是当我尝试以下测试时
package test1;
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
TB.ttt();
TB.ttt2();
}
}
Run Code Online (Sandbox Code Playgroud)
package test1;
public class TA {
static public Boolean ttt()
{
System.out.println("TestInheritenceA");
return true;
}
static public String test ="ClassA";
}
Run Code Online (Sandbox Code Playgroud)
package test1;
public class TB extends TA{
static public void ttt2(){
System.out.println(test);
}
}
Run Code Online (Sandbox Code Playgroud)
它打印:
TestInheritenceA ClassA
所以java静态方法(和字段)有继承(如果你试图调用一个类方法,它会继续寻找类方法的继承链).这不是真的吗?是否有任何继承OO语言与类方法相似?
所以显然静态方法是继承的,但是不能被覆盖,c#也能分享这个问题吗?做其他语言吗?
我一直关注iTunes U上的iPhone开发视频,到目前为止一直很好.我想我理解得很好.
问题是,在他们提供的示例中,他们从不创建自定义类方法,就像您在某些基础类上使用的那些(如[NSString string])所以我不确定如何创建自己的类方法返回我的班级的自动释放实例.
我知道如何使用实例方法创建一个保留对象,但我宁愿使用类方法,因为我更喜欢它,我只是不确定这个实现是否最适合返回一个自动释放的对象:
+ (PhotoViewController*)initWithImageView:(UIImageView*)imageView
{
PhotoViewController *toreturn = [[PhotoViewController alloc] init];
toreturn.imageview = imageView;
[toreturn autorelease];
return toreturn;
}
Run Code Online (Sandbox Code Playgroud)
非常感谢您提供的任何帮助.
例如,我知道Objective-C类方法可以被覆盖而Java不可以.
这有什么好处,还有其他不同之处?
我有一个想要使用CLLocationManager及其某些委托方法的类方法.
从类方法访问委托方法的最佳方法是什么,因为我没有真正的实例级别"self"?我可以实例化一个self并将其用作委托,这将使委托方法运行,但不会显示如何获取数据.什么是最好的方法?
// desired end function, which runs a block when location is found
[SFGeoPoint geoPointForCurrentLocationInBackground:^(SFGeoPoint *geoPoint, NSError *error) {
if (!error) {
// do something with the new geoPoint
NSLog(@"GeoPoint: %@", geoPoint);
}
}];
// SFGeoPoint class, key points
static CLLocationManager *_locationManager = nil;
// get geo point for current location and call block with it
+ (void) geoPointForCurrentLocationInBackground:( void ( ^ )( SFGeoPoint*, NSError* ) ) locationFound {
SFGeoPoint *point = [[SFGeoPoint alloc] init];
_locationManager = [[CLLocationManager alloc] …Run Code Online (Sandbox Code Playgroud) 根据我读到的内容,类方法与静态方法大致相同,只有少数例外但具有提供类指针的优点.
因此,如果在类中定义了非实例方法,是否真的有理由在类方法上使用静态方法?
编辑:由于你们中的一些人很快将其视为与另一个问题的重复.这不是关于类和静态方法之间差异的问题.相反,在绝大多数情况下,当它们的功能重叠时,如何在两者之间做出决定是一个问题.
编辑#2:我问的原因是我正在重构其他人的一些现有代码.具体来说,有些子类与父级共享相同的模块,我打算将它们移动到单独的模块中.发生这种情况时,需要修复静态方法中对类外常量的引用.我可以通过以下方式之一完成此操作1.从父模块导入所有常量2.将所有常量移动到父类中,并将所有子静态方法更改为类方法3.添加"ParentClass".在每次引用常量之前
我个人想做#2,因为它避免了命名空间污染,这也是我问这个问题的原因.这主要是风格问题.希望这提供了足够的背景.
我想在Python中为一个类变量赋一个静态方法,下面就是我的代码.
class Klass:
classVariable = None
@staticmethod
def method():
print "method called"
Klass.classVariable = Klass.method
Klass.method()
Klass.classVariable()
Run Code Online (Sandbox Code Playgroud)
这给了我最后一行的错误,
TypeError: unbound method method() must be called with Klass instance as first argument (got nothing instead).
但是当我将静态方法更改为类方法时,它可以工作.任何人都可以告诉我为什么会这样吗?
假设我有一个带有静态方法的类,并且我希望将类属性设置为该方法返回的值:
class A:
@staticmethod
def foo():
return 12
baz = foo()
Run Code Online (Sandbox Code Playgroud)
但是这样做我得到一个错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in A
TypeError: 'staticmethod' object is not callable
Run Code Online (Sandbox Code Playgroud)
我找到了解决这个问题的方法:
class A:
class B:
@staticmethod
def foo():
return 2
baz = B.foo()
Run Code Online (Sandbox Code Playgroud)
但例如,如果我写:
class A:
class B:
@staticmethod
def foo():
return 2
class C:
baz = B.foo()
Run Code Online (Sandbox Code Playgroud)
我也收到一个错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in …Run Code Online (Sandbox Code Playgroud) 我正在努力找到一种方法来factory_boy使用定义为a的备用构造函数来创建类Factory(我使用版本2.11.1和Python 3)@classmethod.
因此,假设我们有一个用于构建具有默认构造函数的2D点对象的类,另外还有2个:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
@classmethod
def fromlist(cls, coords): # alternate constructor from list
return cls(coords[0], coords[1])
@classmethod
def duplicate(cls, obj): # alternate constructor from another Point
return cls(obj.x, obj.y)
Run Code Online (Sandbox Code Playgroud)
我创建了一个基本的Point工厂:
import factory
class PointFactory(factory.Factory):
class Meta:
model = Point
inline_args = ('x', 'y')
x = 1.
y = 2.
Run Code Online (Sandbox Code Playgroud)
默认情况下,它似乎调用__init__类的构造函数,这似乎非常合乎逻辑.我不能找到一种方法,通过inline_args为coords使用可选的构造fromlist.有办法吗?
这是我第一次在工作和建造工厂的经历,所以我也可能在网上查找错误的关键字......
我希望能够在 Typescript 中使用基于类的方法 - 即在基类上定义的方法,当在子类上调用时,可以访问调用它的子类。这种行为在 Python 中是可能的,但据我所知,在 Typescript 中没有等价物。在 Typescript 中复制它的最佳方法是什么?
示例(在 Python 中):
这个例子(用 Python 编写)演示了我可能想用它做的事情。
# Base class
class Model:
objects = []
def __init__(self, objId):
self.objId = objId
Model.objects.append(self)
@classmethod
def getById(cls, objId):
# Method can access subclass using "cls" parameter
objects = [obj for obj in cls.objects if obj.objId == objId]
if len(objects) > 0:
return objects[0]
else:
print("error")
# Subclass
class Foo(Model):
def __init__(self, objId, name):
self.objId = objId
self.name = name
Foo.objects.append(self)
Foo(1, "foo") …Run Code Online (Sandbox Code Playgroud) class-method ×10
python ×5
objective-c ×3
inheritance ×2
java ×2
block ×1
class ×1
delegates ×1
factory-boy ×1
iphone ×1
oop ×1
python-3.x ×1
static ×1
subclass ×1
superclass ×1
testing ×1
typescript ×1