Python类没有使用def __init __(self)

dma*_*man 21 python class

我正在写一系列文本菜单.下面的类和子类运行没有问题.但我正在审查我的编码,我想知道......我没有def __init__(self)在课堂上使用它是否可以?我应该将数据成员放在def __init__(Self):self.images =(),self.options =()中吗?如果我这样做那么我就不能使用abc模块进行约束,对吗?

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
        )
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 16

你的代码非常好.你不具备有一个__init__方法.

__init__即使使用ABC,您仍然可以使用.ABC元测试的所有内容都是名称已经定义.images在an __init__中设置需要您定义一个类属性,但您可以首先将其设置为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()
Run Code Online (Sandbox Code Playgroud)

现在你可以在ABC上设置约束,要求images抽象属性可用; 在images = None类属性将满足该约束.


小智 5

Your code is fine. The example below shows a minimal example. You can still instantiate a class that doesn't specify the __init__ method. Leaving it out does not make your class abstract.

class A:
    def a(self, a):
        print(a)
ob = A()
ob.a("Hello World")
Run Code Online (Sandbox Code Playgroud)

  • 请为您的代码提供上下文。仅包含代码而没有解释和/或注释的答案不是很有用。 (13认同)