包含其他类的超级结构/类,可以轻松传递

时间:2014-07-30 19:33:55

标签: python class oop inheritance

这个数据结构是否可以使用类以及它在Python中调用的内容?

   class AwesomeThing():

       class Tv():
           tvid = ""
           queue = ""

       class Remote():
           remoteid = ""

       class Channel():
           channelid = ""

       class User():
           userid = ""

       class Comment():
           commentid = ""

       class Scene():
           sceneid = ""
           sceneurl = ""

然后我可以得到一个像这样的实例......

     stream = AwesomeThing()

并将数据设置为其中的类......

     stream.comment.msg = "that's cool"
     stream.user.userid = "EJJ1231"
     stream.channel.channelid = "#reactive"
     stream.scene.sceneurl = "http://coolvideo/iwanna?play.com"

然后将整个实例与所有类及其数据集一起发送到函数...

     playyoutube(stream)

1 个答案:

答案 0 :(得分:2)

是的,但您必须为Stream类提供一个构造函数(__init__),它将嵌套类的实例创建为AwesomeThing类的属性。例如,如果我有这个类:

class Post:
    class Score:
        upvotes = 0
        downvotes = 0

我必须在Score类构造函数中初始化Post类的实例:

class Post:
    class Score:
        upvotes = 0
        downvotes = 0
    def __init__(self):
        self.score = Score()

然后我可以执行这样的代码:

my_post = Post()
my_post.score.upvotes = 8

因此,在您的代码中,您必须将其添加到AwesomeThing类中:

def __init__(self):
    self.tv = Tv()
    self.remote = Remote()
    self.channel = Channel()
    self.user = User()
    self.comment = Comment()
    self.scene = Scene()