如果我想使用Python2.7
创建程序,请执行以下操作:
1)有三个类,即标记,评论和发布
2)self.content
和Tagging
课程的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 Posting
和class Tagging
,但我认为仅使用一个class Commenting
variable
class Posting
的继承是不合逻辑的。
有人能建议我更好的方式吗?
还有一个问题:班级Tagging
和班级Commenting
与班级Aggregation
有Posting
的关系吗?或者它是Association
关系? (UML的单词定义)
答案 0 :(得分:0)
如果你想在OOP中确保一组类提供服从某个合同,你通常会定义一个接口。
Python不直接提供接口,而是通过使用isinstance或hasattr这样的方式来使用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
通过这种方式,您可以将来自“标记”和“评论”的内容从“发布”转换为“契约”,或者我对您的需求是错误的?