我有一个名为SocialPlatform
类:可以Python类与父CLASSE共享变量
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
继承threee其他类:
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
我的想法是,每次递增nb_post
的SocialPlatform
的实例已创建。我因子评分这个变量是所有从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中做到这一点?