Python Classes without using def __init__(self)
我正在写一系列的文本菜单。对于下面的类和子类,它运行时没有问题。但是我在复习我的代码,我想……我在课堂上没有使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | 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 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 def create_servers(self): create_server.create(self) options = ( get_images, get_foo, create_servers ) |
你的代码很好。您不必使用
即使使用ABC,也可以使用
1 2 3 4 5 6 7 8 9 | 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() |
现在,您可以在ABC上设置约束,要求
1 2 3 4 5 | class A: def a(self, a): print(a) ob = A() ob.a("Hello World") |