将变量的值从一个不相关的类转移到另一个

时间:2014-01-04 09:49:06

标签: oop inheritance python-2.7

如果我想使用Python2.7创建程序,请执行以下操作:

1)有三个类,即标记,评论和发布

2)self.contentTagging课程的Commenting将发送到课程self.compact的{​​{1}}

Posting

我尝试将class Tagging: # Handles Tagging - Create new Tags def __init__(self): self.content = [] self.initialTag = "" def doTag(self): #Tag people self.initialTag = raw_input("Name to Tag: ") self.content.append(self.initialTag) #Tagging can only be done if the user created new post. class Commenting: #Handles Commenting - Create new Comments def __init__(self): self.content = [] self.initialComment = "" def doComment(self): #Commenting on Posts self.initialComment = raw_input("Comment: ") self.content.append(self.initialComment) #Commenting can only be done on Posts. No Post means no Comment. (Same goes to Tags) class Posting: #Handles Posting - Create new Posts def __init__(self): self.content = [] #Content of the post self.initialPost = "" self.compact = [] #Post that contains the Post, Comments, and Tags #How do I do this? def doPost(self): self.initialPost = raw_input("Post: ") self.content.append(self.initialPost) 继承到class Postingclass Tagging,但我认为仅使用一个class Commenting variable class Posting的继承是不合逻辑的。

有人能建议我更好的方式吗?

还有一个问题:班级Tagging和班级Commenting与班级AggregationPosting的关系吗?或者它是Association关系? (UML的单词定义)

2 个答案:

答案 0 :(得分:0)

如果你想在OOP中确保一组类提供服从某个合同,你通常会定义一个接口。

Python不直接提供接口,而是通过使用isinstancehasattr这样的方式来使用duck-type,这意味着,如果你的对象有内容属性使用它,如果没有,则引发错误。

从Python 2.6开始,可以通过Abstract Base Classes

获得模拟接口的另一种可能性

希望这有帮助。

答案 1 :(得分:0)

这个怎么样,只是“__ main __”部分中的示例代码:

class Tagging: # Handles Tagging - Create new Tags
    def __init__(self):
        self.content = []
        self.initialTag = ""
    def doTag(self): #Tag people
         self.initialTag = raw_input("Name to Tag: ")
         self.content.append(self.initialTag)
    #Tagging can only be done if the user created new post.

class Commenting: #Handles Commenting - Create new Comments
    def __init__(self):
        self.content = []
        self.initialComment = ""
    def doComment(self): #Commenting on Posts
        self.initialComment = raw_input("Comment: ")
        self.content.append(self.initialComment)
    #Commenting can only be done on Posts. No Post means no Comment. (Same goes to Tags)

class Posting: #Handles Posting - Create new Posts
    def __init__(self, TaggingContent, CommentingContent):
        self.content = [] #Content of the post
        self.initialPost = ""
        self.compact = TaggingContent + CommentingContent #Post that contains the Post, Comments, and Tags
        #How do I do this?

    def doPost(self):
        self.initialPost = raw_input("Post: ")
        self.content.append(self.initialPost)

if __name__ == "__main__":
    T = Tagging()
    C = Commenting()
    ##Do stuff here with tagging and commenting....
    P = Posting(T.content, C.content)
    #Do stuff with posting

通过这种方式,您可以将来自“标记”和“评论”的内容从“发布”转换为“契约”,或者我对您的需求是错误的?