在任何事件之后+doSomething:(id)sender,如何让UIButton在课堂上执行我的类方法?我可以像我一样使用实例方法吗?MyClassUIControlEventTouchDown-addTarget:action:forControlEvents:
提前致谢.
假设我有一个名为MyBaseClass的Objective-C类和一个名为MySubclassedClass的子类.
MyBaseClass有两个类方法:
+ (UIColor *)backgroundColor;
+ (UIImage *)backgroundImage;
Run Code Online (Sandbox Code Playgroud)
backgroundColor方法调用backgroundImage.如果它被限制在MyBaseClass中,我的backgroundColor方法看起来就像
+ (UIColor *)backgroundColor {
UIImage *img = [MyBaseClass backgroundImage];
// irrelevant
return color;
}
Run Code Online (Sandbox Code Playgroud)
但我希望能够将MyBaseClass子类化为MySubclassedClass.backgroundColor不会改变,总是调用父backgroundImage方法.在这种情况下,backgroundImage将在每个子类中重写.
如果1backgroundColor1是一个实例方法,我只会使用
UIImage *img = [[self class] backgroundImage];
Run Code Online (Sandbox Code Playgroud)
但是,当它是静态方法时,我没有"自我"可以使用.
我可以在Objective-C中实现这一目标吗?
说有:
class A(B):
...
Run Code Online (Sandbox Code Playgroud)
这里B可能是object和...是不是:
@classmethod # or @staticmethod
def c(cls): print 'Hello from c!'
Run Code Online (Sandbox Code Playgroud)
我不得不做什么叫A.c()不会触发AttributeError?
换句话说,我知道可以在运行时手动将类方法添加到类中.但是有可能自动这样做,比如每次缺少类方法时都会创建一些虚拟方法吗?
换句话说,只有我可以A.__dict__用我的dict 替换处理__getitem__- 但A.__dict__似乎不可写......
如果我在rails活动模型方法上调用一个方法,如下所示:
class Foo < ActiveRecord::Base
end
Foo.first
Run Code Online (Sandbox Code Playgroud)
我会回来第一个活跃的记录.我不必实例化该类.
但是,如果我创建自己的类并调用方法,我会得到一个例外:
class Person < ActiveRecord::Base
def greeting
'hello'
end
end
Person.greeting
#EXCEPTION: undefined method `greeting' for Person:Class
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题呢?
我在python模块中有一个对象层次结构,如下所示:
class BaseObject(object):
initialized = False
def __init__(self):
self._initialize()
@classmethod
def _initialize(cls):
print "cls.initialized = "+str(cls.initialized)
if not cls.initialized:
cls.x = 1
cls.initialized = True
class ObjectOne(BaseObject):
@classmethod
def double_x(cls):
cls.x = cls.x * 2
print cls.x
class ObjectTwo(BaseObject):
@classmethod
def triple_x(cls):
cls.x = cls.x * 3
print cls.x
if __name__ == '__main__':
obj_1 = ObjectOne()
obj_1.double_x()
obj_2 = ObjectTwo()
obj_2.triple_x()
Run Code Online (Sandbox Code Playgroud)
当我运行这个模块时,我希望输出为:
cls.initialized = False
2
cls.initialized = True
6
Run Code Online (Sandbox Code Playgroud)
但我得到的是:
cls.initialized = False
2
cls.initialized = False
3
Run Code Online (Sandbox Code Playgroud)
我不明白什么?
假设我有一堂课
class SimpleGenerator(object):
@classmethod
def get_description(cls):
return cls.name
class AdvancedGenerator(SimpleGenerator):
@classmethod
def get_description(cls):
desc = SimpleGenerator.get_description() # this fails
return desc + ' Advanced(tm) ' + cls.adv_feature
Run Code Online (Sandbox Code Playgroud)
现在我已经扩展了上面的每个类,每个类都有一个具体的类:
class StringGenerator(SimpleGenerator)
name = 'Generates strings'
def do_something():
pass
class SpaceShuttleGenerator(AdvancedGenerator)
name = 'Generates space shuttles'
adv_feature = ' - builds complicated components'
def do_something():
pass
Run Code Online (Sandbox Code Playgroud)
现在让我说我打电话
SpaceShuttleGenerator.get_description()
Run Code Online (Sandbox Code Playgroud)
问题在于,AdvancedGenerator我希望在SimpleGenerator传递类的实例时调用该方法,具体而言SpaceShuttleGenerator.可以这样做吗?
注意:示例是简化的,因为我的具体示例涉及更多.让我们说我的目标不是连接字符串.
我已经熟悉了这个概念,最值得注意的是观看了Raymond Hettinger的精彩视频并阅读了这里接受的答案,我想知道我的错误.
class ReadHTML(object):
def __init__(self, url):
page = urlopen(url).read()
self.page = page
@classmethod
def from_file(cls, path):
page = open(path).read()
return cls(page)
Run Code Online (Sandbox Code Playgroud)
这有效
r = ReadHTML('http://example.com')
print r.page
Run Code Online (Sandbox Code Playgroud)
而事实并非如此
r = ReadHTML.from_file('example.html')
print r.page
Run Code Online (Sandbox Code Playgroud)
它抛出一个错误,好像我试图"urlopen"文件:
File "/usr/lib/python2.7/urllib2.py", line 258, in get_type
raise ValueError, "unknown url type: %s" % self.__original
ValueError: unknown url type: <!doctype html>
Run Code Online (Sandbox Code Playgroud)
你能看出什么是错的吗?
为了整洁和可重用性,我正在考虑在一个类中放入一堆实用程序方法.该类不需要任何自己的属性,因此我将方法定义为类方法; 我认为没有真正需要让这个类的实例浮动...
......还是在那儿?效率有差异吗?(一个引人注目的?)或者调用类方法的行为方式与调用类的一部分相同吗?
我有以下型号:
class ActivityLog < ActiveRecord::Base
validates :user_id, :instance_id, :action, presence: true
validates :user_id, :instance_id, :action, numericality: true
def log
ActivityLog.create(
user_id: current_user ? current_user.id : -1,
instance_id: instance_id,
action: actions.index(action)
)
end
private
def actions
['start','stop','create','destroy']
end
end
Run Code Online (Sandbox Code Playgroud)
当我从rails控制台调用以下行时,出现错误:
ActivityLog.log(user_id: 1, instance_id:1, action: 'create')
# Error returned from console
NoMethodError: undefined method `log' for #<Class:0x007fb4755a26a8>
Run Code Online (Sandbox Code Playgroud)
为什么我的方法调用不起作用?我在课堂上定义了它,但它说它是未定义的.我错过了什么或误解了什么?谢谢.
可以直接在类型上调用A classmethod,无论是内联定义还是in的一部分metaclass:
class eggs( type ):
def f1( cls ):
print( "eggs" )
class spam( metaclass = eggs ):
@classmethod
def f2( cls ):
print( "spam" )
f = spam()
type(f).f2() #--> spam
type(f).f1() #--> eggs
Run Code Online (Sandbox Code Playgroud)
但是,似乎classmethod无法在实例上调用元类中的定义:
f.f2() #--> spam
f.f1() #--> AttributeError
Run Code Online (Sandbox Code Playgroud)
为什么是这样?
class-method ×10
python ×5
objective-c ×3
ruby ×2
superclass ×2
class ×1
events ×1
iphone ×1
metaclass ×1
performance ×1
python-3.x ×1
runtime ×1
subclass ×1
uibutton ×1