Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

python 2.7 - create an instance of one class from another class

I created browserView class named as "bdrMenuView" . It should be like "class bdrMenuView(BrowserView):" . and the class contains the method named as "createPictMenu" . The whole class should be

    class bdrMenuView(BrowserView):
              def createPictMenu(self):

Now i have written one more class named as LogoViewlet . It should be like "class LogoViewlet(ViewletBase):" . and the class contains the method named as "update" . The whole class should be

    class LogoViewlet(ViewletBase):
              def update(self):

Now i want to call the method of browserView class from another class. I created an instance of one class like

    class LogoViewlet(ViewletBase):
              def update(self):
                   a = bdrMenuView(self,BrowserView)      ---------> instance of BrowserView class
                   logoName = a.createPictMenu() 

I want to know whether it is correct or not which i created.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, that is not correct and makes absolutely no sense. Why do you pass in the baseclass as a parameter? Please learn basic Python.

The parameters to views are the context and the request. The best way to make a view from inside another view (which a viewlet is) is to traverse to it. You can do this with restrictedTraverse.

The exact code depends on what your view is registered for. For example, if the view you want to look up is called @@bdrmenu and registered for any content, you would look it up with self.context.restrictedTraverse('@@bdrmenu').


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...