python - python类可以与父类共享变量吗

标签 python inheritance

我有一个名为 SocialPlatform 的类:

class SocialPlatform:
    nb_post = 0

    def __init__(self, data):
        self.data = data
        self._init_type()
        self.id_post = self._init_id_post()

    @classmethod
    def _init_id_post(cls):
        cls.nb_post += 1
        return cls.nb_post

以及从 SocialPlatform 继承的其他三个类:

class Facebook(SocialPlatform):
    _NAME = 'facebook'

    @classmethod
    def get_class_name(cls):
        return cls._NAME

    # code here


class Twitter(SocialPlatform):
    _NAME = 'twitter'

    @classmethod
    def get_class_name(cls):
        return cls._NAME

    # code here


class Instagram(SocialPlatform):
    _NAME = 'instagram'

    @classmethod
    def get_class_name(cls):
        return cls._NAME

    # code here

我的想法是每次创建 SocialPlatform 实例时增加 nb_post 。我认为这个变量在继承自 SocialPlatform

的所有类之间共享

所以我在我的主要功能中测试了这一点:

def main():
    post = Post() # an other class with stuff in it, it doesn't matter here
    social_platform = {
        'facebook': Facebook,
        'twitter': Twitter,
        'instagram': Instagram
    }
    while True:
        try:
            platform = social_platform[post.actual_post['header']['platform']](post.actual_post['data'])
        except KeyError:
            print 'Platform (%s) not implemented yet' % post.actual_post['header']['platform']
            sys.exit(84)

        print 'platform name : ' + platform.get_class_name()
        print 'post id : ' + str(platform.id_post)
        # platform.aff_content()

        post.pop()
        if not len(post.post):
            break

        print 'enter return to display next post'
        while raw_input() != "": pass

但是当我使用此代码时,我得到以下输出:

platform name : twitter
post id : 1
enter return to display next post

platform name : facebook
post id : 1
enter return to display next post

platform name : twitter
post id : 2

使用此方法,nb_post 在 Twitter、Facebook 或 Instagram 实例之间共享,而不是全部。

所以我的问题是:有没有办法在 python 中做到这一点?

最佳答案

当某个属性没有找到时,将会在更高的级别上查找。分配时,会使用最本地的级别。

例如:

class Foo:
    v = 1

a = Foo()
b = Foo()

print(a.v) # 1: v is not found in "a" instance, but found in "Foo" class
Foo.v = 2 # modifies Foo class's "v"
print(a.v) # 2: not found in "a" instance but found in class
a.v = 3 # creates an attribute on "a" instance, does not modify class "v"
print(Foo.v) # 2
print(b.v) # 2: not found in "b" instance but found in "Foo" class

此处 _init_id_post 被声明为 classmethod,并且您正在执行 cls.nb_post = cls.nb_post + 1。 在此表达式中,第二个 cls.nb_post 第一次出现时将引用 SocialPlatform,然后您在所引用的 cls 对象上进行分配TwitterInstagram 类,而不是 SocialPlatform。 当您在同一个类上再次调用它时,第二次 cls.nb_post 出现将不会引用 SocialPlatform,因为您在 Twitter< 级别创建了属性 类(例如)。

解决方案不是使用 cls,而是使用 SocialPlatform.nb_post += 1(并使其成为 @staticmethod)

关于python - python类可以与父类共享变量吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39772625/

相关文章:

javascript - 多重继承和多次调用父构造函数

python - 如何在字符串中查找项目的索引?

python - 如何在 python 类上创建带参数的装饰函数?

python - 如何在 python 中使用 yield 函数

oop - Go中扩展类型的访问方法

c# - 获取抽象类的所有继承类

python - SciPy 曲线拟合参数的方差到底是多少? (Python)

python - 尽管文件显示在存储桶中,但 Blobstore 上传的 get_uploads 返回空列表

javascript - 如何在 Typescript 中显式识别全局命名空间中的实体?

c# - 返回自身类型的方法的接口(interface)