简体   繁体   English

在Python中将一个类导入另一个类

[英]Importing a class into another class in Python

as I'm still learning python I came up to a problem. 因为我还在学习python,所以遇到了一个问题。

Why does this work: 为什么这样做:

class SomeOtherClass(object):
    def __init__(self):
        self.number = 10
        print(self.number)

    def increase(self):
        self.number += 1
        print(self.number)

class MyMainClass(object):
    def __init__(self):
        self.otherClass = MyClass()

app = MyMainClass() #Output: 10
app.otherclass.increase() #Output: 11

but this doesn't: 但这不是:

from tkinter import *

class MyMainClass(object):
    def __init__(self):
        self.tk = Tkinter() # <-- Error: see below.

app = MyMainClass()
app.tk.title("My window")
...

Both times I include a class, but in the second example it says: 两次我都包含一个类,但是在第二个示例中它说:

NameError: global name 'Tkinter' is not defined NameError:全局名称“ Tkinter”未定义

Where's the difference between those examples and how can I solve this, so I'm able to use tkinter in my class? 这些示例之间有什么区别,我该如何解决,所以我可以在课堂上使用tkinter吗?

Thanks for your help. 谢谢你的帮助。

Perhaps you meant Tk() ? 也许您是说Tk()吗? the tkinter module on Python 3.x does not seem to contain a class Tkinter . Python 3.x上的tkinter模块似乎不包含Tkinter类。

As to the meaning of your question and example... well, the examples are absolutely irrelevant, and the question should simply be "why can't I create an instance of Tkinter " or something. 至于你的问题,例如的意思......好吧,这些例子是绝对无关,问题应该仅仅是“我为什么不能创建一个实例Tkinter ”什么的。

Python Lesson: This is also a good example of why it's a bad idea to use star imports (ie from <module> import * , because * looks like a star). Python的教训:这也是为什么这是一个坏主意,使用星进口一个很好的例子(即from <module> import * ,因为*看起来像一个明星)。 This imports everything from tkinter , but doesn't let you know if something you thought was there actually isn't 这将从tkinter导入所有内容,但不会让您知道您认为那里确实没有的东西

from tkinter import *

whereas this 而这

from tkinter import Tkinter

would have immediately pointed out that (the class) Tkinter does not exist in tkinter . 会马上指出,(类) Tkinter不存在tkinter Another option that some seem to prefer (incl. myself in some cases), is import tkinter followed by tkinter.Tk() , which has the advantage that it's obvious where a class comes from. 某些人似乎更喜欢的另一个选项(在某些情况下包括我自己)是import tkinter tkinter.Tk() ,后跟tkinter.Tk() ,它的优点是显而易见类的来源。 Futhermore, PEP8 also discourages the use of star imports (referring to them as "wildcard imports"). 此外, PEP8还不鼓励使用星号导入(将其称为“通配符导入”)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM