看看下面的代码:
class A(object):
defaults = {'a': 1}
def __getattr__(self, name):
print('A.__getattr__')
return self.get_default(name)
@classmethod
def get_default(cls, name):
# some debug output
print('A.get_default({}) - {}'.format(name, cls))
try:
print(super(cls, cls).defaults) # as expected
except AttributeError: #except for the base object class, of course
pass
# the actual function body
try:
return cls.defaults[name]
except KeyError:
return super(cls, cls).get_default(name) # infinite recursion
#return cls.__mro__[1].get_default(name) # this works, though
class B(A):
defaults = {'b': 2}
class C(B):
defaults = {'c': 3}
c = C()
print('c.a …Run Code Online (Sandbox Code Playgroud) 抽象基类在Python中仍然可以派上用场.在编写一个抽象基类,我希望每个子类都有一个spam()方法,我想写这样的东西:
class Abstract(object):
def spam(self):
raise NotImplementedError
Run Code Online (Sandbox Code Playgroud)
挑战还包括想要使用super(),并通过将其包含在整个子类链中来正确地完成.在这种情况下,似乎我必须super包括如下所示的每个调用:
class Useful(Abstract):
def spam(self):
try:
super(Useful, self).spam()
except NotImplementedError, e:
pass
print("It's okay.")
Run Code Online (Sandbox Code Playgroud)
这对于一个简单的子类来说没问题,但是当编写一个有很多方法的类时,try-except会变得有点麻烦,而且有点难看.是否有更优雅的抽象基类子类化方法?我只是做错吗?
简单的问题.我创建了一个名为Tester1的类,它扩展了另一个名为Tester2的类.Tester2包含一个名为"ABC"的公共字符串.
这是Tester1:
public class Tester1 extends Tester2
{
public Tester1()
{
ABC = "Hello";
}
}
Run Code Online (Sandbox Code Playgroud)
如果我改为将第5行更改为
super.ABC = "Hello";
Run Code Online (Sandbox Code Playgroud)
我还在做同样的事吗?
当我扩展Sprite时,我总是不调用super().
但是不会not calling super()造成任何问题吗?
直到现在,我没有任何问题,我从未见过在构造函数中调用super()的代码,该类扩展了Sprite.
TextField怎么样?
我对TextField也没有任何问题.
如何知道我是否应该调用super()?
我读到接口没有构造函数,这意味着它不会调用其超类的super().我还读到Java中的每个类都是它的子类Object
那么接口呢,它是Object的子类吗?为什么?
我正在制作一个Android应用程序,用于测试手机上的某些安全功能是否已启用.例如,如果您启用了密码登录,或者您的手机上的数据已加密.
出于某种原因,应用程序必须运行两次才能测试并查看是否在手机上启用了这些安全功能,这是我正在尝试解决的问题.我希望它能够测试并查看在创建应用程序时以及第一次运行应用程序时是否启用了安全功能,而不是第二次运行应用程序.
我测试onStart()我的MainActivity文件中的函数是否启用了这些功能.我在下面列出了函数代码:
@Override
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@SuppressLint("NewApi")
public void onStart()
{
super.onStart();
//determine if phone uses lock pattern
//It returns 1 if pattern lock enabled and 0 if pin/password password enabled
ContentResolver cr = getBaseContext().getContentResolver();
lockPatternEnable = Settings.Secure.getInt(cr, Settings.Secure.LOCK_PATTERN_ENABLED, 0);//Settings.System
//returns 1 if pin/password protected. 0 if not
KeyguardManager keyguardManager = (KeyguardManager) getBaseContext().getSystemService(Context.KEYGUARD_SERVICE);
if( keyguardManager.isKeyguardSecure())
{
//it is pin or password protected
pinPasswordEnable=1;
}
else
{
//it is not pin or password protected
pinPasswordEnable=0;
}//http://stackoverflow.com/questions/6588969/device-password-in-android-is-existing-or-not/18716253#18716253
//determine if …Run Code Online (Sandbox Code Playgroud) 假设我有一些Python代码:
class Mother:
def __init__(self):
print("Mother")
class Father:
def __init__(self):
print("Father")
class Daughter(Mother, Father):
def __init__(self):
print("Daughter")
super().__init__()
d = Daughter()
Run Code Online (Sandbox Code Playgroud)
此脚本打印"女儿".反正是否确保调用基类的所有__init__方法?我想出的一个方法是:
class Daughter(Mother, Father):
def __init__(self):
print("Daughter")
for base in type(self).__bases__:
base.__init__(self)
Run Code Online (Sandbox Code Playgroud)
这个脚本打印"女儿","母亲","父亲".使用super()或其他方法有一个很好的方法吗?
在运行时的方法中,有没有办法知道是否已super在子类中调用该方法?例如
module SuperDetector
def via_super?
# what goes here?
end
end
class Foo
include SuperDetector
def bar
via_super? ? 'super!' : 'nothing special'
end
end
class Fu < Foo
def bar
super
end
end
Foo.new.bar # => "nothing special"
Fu.new.bar # => "super!"
Run Code Online (Sandbox Code Playgroud)
我怎么写via_super?,或者,如果有必要的话via_super?(:bar)?
我在项目中遇到了一个奇怪的问题.现在我简化了问题并在这里写了一个小例子来说明我的困惑:
public class Question {
class Q1 {}
class Q2 extends Q1 {}
interface In<T> {
void f(T t);
}
List<Q2> list;
void f(In<? super List<? super Q2>> in) {
in.f(list);
}
static void g() {
Question question = new Question();
In<Collection<Q1>> in1 = new In<Collection<Q1>>() {
@Override
public void f(Collection<Q1> o) {}
};
In<List<Q2>> in2 = new In<List<Q2>>() {
@Override
public void f(List<Q2> o) {}
};
question.f(in1); //Error!
question.f(in2); //Error!
}
}
Run Code Online (Sandbox Code Playgroud)
我的目标是使该方法f(In<? super List<? super Q2>>)更灵活.我可以通过 …
我有一个构造函数,它获取HashSet和HashMap.我需要在一个hashMAp上运行验证检查并将其与hashSet结合使用,因为'super'必须只接收一个hashSet.因为我得到以下错误,我无法找到方法:cannot reference this before supertype constructor
例:
public class A extends B {
public A(HashSet<Obj> h1, HashMap<UID,Objects> m1) {
super(new C (h1) ); //h1 should contain changes related to m1..
}
Run Code Online (Sandbox Code Playgroud)
我想做那样的事情:
public class A extends B {
public A(HashSet<Obj> h1, HashMap<UID,Objects> m1) {
runMyFunc(h1,m1);
super(new C (h1) );
}
runMyFunc(HashSet<Obj> h1, HashMap<UID,Objects> m1){
//do checks
//more checks...
// if something then h1.setUid(m1.get(0))...
return h1;
}
Run Code Online (Sandbox Code Playgroud)
我想将构造函数转换为私有,然后像这样运行它:
public class A extends B {
private A(HashSet<Obj> h1) {
super(new C …Run Code Online (Sandbox Code Playgroud)