2016-09-29 6 views
1

私はSocialPlatformをという名前のクラスがあります。缶Pythonのクラスは、親クラッセで変数を共有する

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のインスタンスが作成されました。

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 
私は、この変数がだから私は私の主な機能であることをテストし SocialPlatform

から継承するすべてのクラスの間で共有されていました取り払わ

nb_postは、Twitter、Facebook、Instagramインスタンス間で共有されています。

私の質問です:これはPythonでこれを行う方法はありますか?

答えて

1

属性がある場合には見つからない場合、それはより高いレベルで検索されます。割り当て時には、最もローカルなレベルが使用されます。例えば

:ここ

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_postclassmethod宣言された、とあなたはcls.nb_post = cls.nb_post + 1をやっています。 この式では、2番目のcls.nb_postが最初にSocialPlatformを参照し、TwitterまたはInstagramクラスを参照しているclsオブジェクトがSocialPlatformではなく割り当てられます。 同じクラスでもう一度呼び出すと、2番目のcls.nb_post occurenceはTwitterクラス(たとえば)のレベルで属性を作成したので、SocialPlatformを参照しません。

ソリューションはclsを使用しますが、SocialPlatform.nb_post += 1を使う(そしてそれ@staticmethod作る)することではありません

1

あなたが明示的にインクリメント式で基本クラスを参照する必要があります。

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

は次のようになります。1として

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

How to count the number of instance of a custom class?

1
class A(): 
     n = 0 

     def __init__(self): 
      A.n += 1 



    class B(A): 

     def __init__(self): 
      super(B, self).__init__() 


    class C(A): 

     def __init__(self): 
      super(C, self).__init__() 


a = A() 
print(a.n) #prints 1 
b = B() 
print(a.n) #prints 2 
c = C() 
print(a.n) #prints 3 

私は、あなたが自分で残りの部分を把握することができると思います。がんばろう!

0

これは私のために動作します。その後、

class SocialPlatform(object): 
    nb_post = 0 
    def __init__(self): 
    self.id_post = A.nb_post 
    A.increment() 

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

class Facebook(SocialPlatform): 
    pass 

class Twitter(SocialPlatform): 
    pass 

そして:

>>> a = Facebook() 
>>> b = Twitter() 
>>> c = Twitter() 
>>> 
>>> a.id_post 
0 
>>> b.id_post 
1 
>>> c.id_post 
2 
関連する問題