类属性的继承(Python)

7

有没有办法实现这样的功能?我使用Python,但不确定其他编程语言是否可以实现...

class Parent():
    class_attribute = "parent"

    @staticmethod
    def class_method():
        print __class__.class_attribute

class Child(Parent):
    class_attribute = "child"

我知道不能直接调用__class__。这只是一个例子,因为我想要像引用类本身一样的东西,因为我希望子类根据其类属性表现出不同的行为。

然后期望的输出应该像这样:

> Parent.class_method()
"parent"
> Child.class_method()
"child"

我知道相同的技术可以通过实例来实现。但我不想创建实例,因为有时 __init__ 方法中的代码可能会很长而且要求很高,如果我想经常调用 class_method,我就必须创建大量仅用于这个方法调用的实例。而且因为 class_attributeclass_method 是静态的,并不会被实例更改。


你是在说普通的 static 函数吗? - Tigran
2个回答

10

听起来你想要一个类方法,这可以通过使用 classmethod 装饰器来实现:

class Parent(object):
    class_attribute = "parent"

    @classmethod
    def class_method(cls):
        print cls.class_attribute

class Child(Parent):
    class_attribute = "child"


>>> Parent.class_method()
parent
>>> Child.class_method()
child

或者,正如bgporter所指出的那样,您可以直接使用属性完成,完全不需要使用方法。


但是考虑到文档:“如果为派生类调用类方法,则将派生类对象作为隐含的第一个参数传递”,这是否意味着派生类对象将被创建?因为OP说想避免实例构造。 - Tigran
我想调用这个方法,因为在这个方法中的代码可能会执行更复杂的操作而不仅仅是打印属性。我认为,提供一个更简单的例子可以更容易地解释我的需求,所以@classmethod是一个解决方案。 - davekr
2
@Tigran 不是的。一个类本身就是一个对象(实际上是其元类的一个实例)。 - Daniel Roseman
@DanielRoseman:啊,好的,那正是我想的。+1 - Tigran

4

Python中,无论是否创建实例,它都可以正常工作:

>>> class Parent(object):
...    attribute = "parent"
... 
>>> class Child(Parent):
...    attribute = "child"
... 
>>> p = Parent()
>>> p.attribute
'parent'
>>> c = Child()
>>> c.attribute
'child'
>>> Parent.attribute
'parent'
>>> Child.attribute
'child'
>>> 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接