2013-06-26 5 views
16

私は一連のテキストメニューを書いています。下のクラスとサブクラスでは問題なく実行されます。しかし私は私のコーディングを見直していて、私は疑問に思っています....私はクラスでdef __init__(self)を使用していないのは大丈夫ですか? self.images =()、self.options =()などのデータメンバーをdef __init__(Self):に配置する必要がありますか?もし私がそれをしたら、拘束のためにabcモジュールを使用することはできませんでしたか?def __initを使用しないPythonクラス__(self)

class BaseMenu(object): 
    __metaclass__ = abc.ABCMeta 

    @abc.abstractproperty 
    def options(self): 
     pass 

    @abc.abstractproperty 
    def menu_name(self): 
     pass 

    def display(self): 
     header = "FooBar YO" 
     term = getTerminalSize() 
     #sys.stdout.write("\x1b[2J\x1b[H") 
     print header.center(term, '*') 
     print self.menu_name.center(term, '+') 
     print "Please choose which option:" 
     for i in self.options: 
      print(
       str(self.options.index(i)+1) + ") " 
       + i.__name__ 
      ) 
     value = int(raw_input("Please Choose: ")) - 1 

     self.options[value](self) 

class Servers(BaseMenu): 

    menu_name = "Servers" 
    images =() 
    foo =() 

    def get_images(self): 
     if not self.images: 
      self.images = list_images.get_images() 
     for img in self.images: 
      print (
       str(self.images.index(img)+1) + ") " 
       + "Name: %s\n ID: %s" % 
       (img.name, img.id) 
       ) 

    def get_foo(self): 
     if not self.foo: 
      self.foo = list_list.get_list() 
     for list in self.foo: 
      print "Name:", list.name 
      print " ID:", list.id 
      print 

    def create_servers(self): 
     create_server.create(self) 

    options = (
     get_images, 
     get_foo, 
     create_servers 
     ) 

答えて

11

コードは完全に問題ありません。 には__init__メソッドを持つがありません。

__init__は、ABCでも使用できます。 という名前のが定義されている場合のABCメタテストのすべてです。 __init__ないでimagesを設定すると、クラス属性を定義する必要がありますが、最初にNoneにそれを設定することができます。今すぐ

class Servers(BaseMenu): 

    menu_name = "Servers" 
    images = None 
    foo = None 

    def __init__(self): 
     self.images = list_images.get_images() 
     self.foo = list_list.get_list() 

あなたはimages抽象プロパティが利用可能であることを要求するABCの制約を設定することができます。 images = Noneクラス属性はその制約を満たします。

関連する問題