【问题标题】:How to get a value of string from first class and use in second class如何从第一类获取字符串值并在第二类中使用
【发布时间】:2019-09-07 10:35:14
【问题描述】:

我正在尝试从头等舱获取字符串的值,我想在二等舱使用,但我不知道该怎么做。

我只想访问一等值并在二等中使用。

我已经尝试过getter和setter方法:

  tk = tkinter('rohit')
  print(tk.__getattribute__('length'))

这是我的代码:

class values:
    def __init__(self,root):
        self.root = root
    def run(self):
        name = self.root # <----|I want these values and print in splash class
        age = 20         # <----|
        length = '152cm' # <----| 

class splash:
    def __init__(self, name, age, length):
        self.name = name
        self.age = age
        self.size = length
    def show(self):
       print('Name:%s, Age:%s, length:%s' % (self.name, self.age, self.length)



# call
tk = tkinter('rohit')

tk.?
splash = splash(?)

splash.show()

我排除了结果:

Name:rohit, Age:33, length:152cm

【问题讨论】:

  • try class splash (object): ,在 def show(self) 上返回
  • 不要为实例和类名使用相同的名称 - splash = splash()。对类使用“UpperCaseNames”有很好的规则 - class Splash()class Values() 然后你有 splash = Splash()。查看更多PEP 8 -- Style Guide for Python Code
  • 首先创建值的实例 - item = Values(),然后将其用作类 Splash - splash = Splash(item.root, item.age, item.length) 中的参数,但它们不能是局部变量,而是带有 self. 的类变量。如果您要在Values 中创建Splash,那么您可以使用self. - splash = Splash(self.root, self.age, self..length)

标签: python python-3.x oop tkinter


【解决方案1】:

首先:使用UpperCaseNames 作为类的名称 - class Valuesclass Splash - 以便更容易地识别代码中的类,并且不会覆盖具有不同内容的变量 - 即。 splash = Splash()


Values 中使用self. 来保留值,然后您可以创建Values 的实例以在Splash() 中使用它

items = Values('rohit')
items.run()
splash = Splash(items.name, items.age, items.length)

完整代码:

class Values:

    def __init__(self, root):
        self.root = root

    def run(self):
        self.name = self.root # <----|I want these values and print in splash class
        self.age = 20         # <----|
        self.length = '152cm' # <----| 

class Splash:

    def __init__(self, name, age, length):
        self.name = name
        self.age = age
        self.length = length

    def show(self):
       print('Name:%s, Age:%s, length:%s' % (self.name, self.age, self.length))

items = Values('rohit')
items.run()
splash = Splash(items.name, items.age, items.length)

或者在run()中直接使用Splash()@

class Values:

    def __init__(self, root):
        self.root = root

    def run(self):
        name = self.root # <----|I want these values and print in splash class
        age = 20         # <----|
        length = '152cm' # <----| 
        splash = Splash(name, age, length)
        splash.show()

class Splash:

    def __init__(self, name, age, length):
        self.name = name
        self.age = age
        self.length = length

    def show(self):
       print('Name:%s, Age:%s, length:%s' % (self.name, self.age, self.length))

items = Values('hello')
items.run()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 2015-01-17
    • 1970-01-01
    相关资源
    最近更新 更多