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

时间:2019-09-07 10:35:14

标签: python python-3.x oop tkinter

我正试图从第一堂课中获得一个字符串的值,我想在第二堂课中使用它,但我不知道该怎么做。

  

我只想访问头等舱的值并在二等舱中使用。

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

public class a {
    public static boolean verifyHardwareID(String id) {
        String ch = id.substring(0, 2);
        if (ch == "MS" || ch == "MT" || ch == "KB") {
            return true;
        } else {
            return false;
        }
    }

    public static void main(String[] args) {
        String id = "MT123456";

        if (verifyHardwareID(id)) {
            System.out.print("Valid");
        } else {
            System.out.print("Invalid");
        }
    }
}

这是我的代码:

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

1 个答案:

答案 0 :(得分:1)

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


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

或在Splash()中使用run()直角

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