如何从第一类中获取字符串值并在第二类中使用

2024-04-20 12:10:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从第一类得到一个字符串的值,我想在第二类中使用,但我不知道怎么做。你知道吗

I just want to access first class value and use in second class.

我已经尝试了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

Tags: andnameinselfagetkinterdefroot
1条回答
网友
1楼 · 发布于 2024-04-20 12:10:49

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


Values中使用self.来保留值,然后可以创建值的实例来在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()direclty

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()

相关问题 更多 >