Как назначить класс с оператором if в python - PullRequest
0 голосов
/ 23 сентября 2019

РЕДАКТИРОВАТЬ: да, в приведенном ниже коде есть много ошибок.Я написал это, чтобы проверить идею, которая у меня была, и я не хотел делиться собственным кодом.Я предоставил решение моего вопроса.

У меня есть два разных устройства, которые я использую в лаборатории.Я хотел бы использовать ввод из командной строки, чтобы изменить, какое устройство я использую.Чтобы уточнить, я хотел бы ввести имя устройства, и переменная определяется этим именем в условии if.В настоящее время, когда я пробую приведенный ниже код, я получаю:

AttributeError: у класса temp_class нет атрибута 'get_int'

Что я делаю не так

from classA import*
from classB import*
from temp_class import*

tempC = temp_class()

print tempC

user_input = raw_input()

print user_input

if (user_input == "a") :
    tempC.__del__()
    tempC = class_a(5)
if (user_input == 'b') :
    tempC = class_b(5)
print temp_class

tempC.set_int(5)

print temp_class.get_int()

Вывод кода:

Первый a - это то, что я набрал

Что находится внутри temp_class

class temp_class:

    def __init__(self):
        self.num = 8

Что находится внутри класса A

class class_a(object):

    def __init__(self, int):
        self.num = self.set_int(int)

    def set_int(self, int):
        self.num = int

    def get_int(self):
        return self.num

что внутри class_b

class class_b:

    def __init__(self):
        self.num = 8

Ответы [ 2 ]

1 голос
/ 23 сентября 2019

Существует много проблем с кодом, которым вы поделились.Я постараюсь упростить это:

# prog.py

from device_a import DeviceA
from device_b import DeviceB

user_input = raw_input()  # use input() if you have python3

if (user_input == "a") :
    # no need to create an initial "temp" instance or to delete it
    tempC = DeviceA(5)
elif (user_input == 'b') :
    tempC = DeviceB() # DeviceB doesn't take any parameters

# tempC can either be a DeviceA or DeviceB, but both need to have the same methods defined

try:
    tempC.set_int(5) # this will fail for DeviceB because it has no set_int method
except: # this should have a more specific exception type
    pass

print tempC.get_int() # note that this is the name of the variable, not the class


# device.py
class Device(object):
    def __init__(self, num):
        self.num = num
    def get_int(self):
        return self.num

# device_a.py
from device import Device

class DeviceA(Device):
    def __init__(self, num):  # int is a builtin function, so it shouldn't be used as a parameter name
        super(DeviceA, self).__init__(num)

    def set_int(self, num):
        self.num = num

# device_b.py
from device import Device

class DeviceB(Device):
    def __init__(self):
        super(DeviceB, self).__init__(8)
    # no set_int, as this one seems to be fixed in your example
0 голосов
/ 24 сентября 2019

Прошлой ночью я выяснил, как решить мою проблему.Вот то, что я сейчас использую.

obj_dic = {}

print obj_dic

print("a for class a for class b")

user_input = raw_input(":> ")

if user_input == 'a':
    obj_dic = {'a':class_a()}
else:
    obj_dic = {'b':class_b()}

tempC = obj_dic.get(user_input)

print tempC.get_int()

print tempC
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...