在Python in a Nutshell(第2版)一书中,有一个示例使用
旧样式类来演示如何以经典分辨率顺序解析方法,
以及它与新顺序的不同之处.
我通过重写新样式的示例尝试了相同的示例,但结果与使用旧样式类获得的结果没有什么不同.我用来运行该示例的python版本是2.5.2.以下是示例:
class Base1(object):
def amethod(self): print "Base1"
class Base2(Base1):
pass
class Base3(object):
def amethod(self): print "Base3"
class Derived(Base2,Base3):
pass
instance = Derived()
instance.amethod()
print Derived.__mro__
Run Code Online (Sandbox Code Playgroud)
调用instance.amethod()打印Base1,但根据我对MRO的理解,新类型的输出应该是Base3.通话Derived.__mro__打印:
(<class '__main__.Derived'>, <class '__main__.Base2'>, <class '__main__.Base1'>, <class '__main__.Base3'>, <type 'object'>)
我不确定我对新样式类的MRO的理解是不正确的还是我做了一个我无法察觉的愚蠢错误.请帮助我更好地了解MRO.
如何获得在Python中定义方法的类?
我想要以下示例打印" __main__.FooClass":
class FooClass:
def foo_method(self):
print "foo"
class BarClass(FooClass):
pass
bar = BarClass()
print get_class_that_defined_method(bar.foo_method)
Run Code Online (Sandbox Code Playgroud) 我有一个基类,其中有两个派生自它的类。我希望基类的方法的行为有所不同,具体取决于参数是否与派生类具有相同的类型,或者只是基类的实例但类型不同。这是当前的实现:
class MyBase:
def __init__(self, foo: int):
self.foo = foo
def __eq__(self, other):
return self.foo == other.foo
class MyDerived_1(MyBase):
def __init__(self, foo: int, bar: int):
super().__init__(foo)
self.bar = bar
class MyDerived_2(MyBase):
def __init__(self, foo: int, bar: int):
super().__init__(foo)
self.bar = bar
def __eq__(self, other):
if type(other) == type(self):
return self.bar == other.bar
elif isinstance(other, MyBase):
return super().__eq__(other)
else:
return False
Run Code Online (Sandbox Code Playgroud)
在倒数第四行中,我必须明确引用 MyBase。也许这很好,但我的理解是“super”关键字的一个要点是它应该允许您更改基类,而不必重新编写类中的任何内容。因此,该解决方案的一个潜在问题是,如果 MyBase 发生更改,那么init会很好,因为它调用“super”,但eq不会更新其行为。
所以我尝试用“type(super)”或“type(super())”替换“MyBase”,但这些不引用超类,它们引用对象“super”的类。
请注意,此问题不同于:
获取父类名? 获取Python 3等中未绑定方法对象的定义类。
因为一旦对象被初始化,他们就会寻找父类。
我想我应该能够通过运行 MRO 找到超级类。但这似乎是一个糟糕的解决方案,因为我不是在寻找整个继承树,我只是想知道超类的类型。
有没有办法从“超级”中提取这些信息?
在Python中,我定义了一个类:
class Myclass(BaseModule):
Run Code Online (Sandbox Code Playgroud)
我想要打印参数BaseModule。
像这样:
class Myclass(BaseModule):
logger.info("Argument=%s" % BaseModule.get_name())
Run Code Online (Sandbox Code Playgroud)
不起作用:
unbound method get_name() must be called with BaseModule instance as
first argument (got nothing instead)
Run Code Online (Sandbox Code Playgroud)