[英]Adding a new object to a class with user-input(input) in python
I am trying to add new objects to a class(emne) but the new instances of the class needs to be created using user input. 我正在尝试将新对象添加到类(emne),但是需要使用用户输入来创建类的新实例。 So i need a way to be able to chose the name for the object and set some of the values of the objects with user input.
因此,我需要一种能够选择对象名称并使用用户输入设置对象值的方法。
I have already tried to create a function that passes the value of the user input into ax = emner(x) to create it but it only returns: AttributeError: 'str' object has no attribute 'fagKode' so i think my issue is that the value of the input is created as a string so that it is not understood as a way to create the function 我已经尝试创建一个函数,该函数将用户输入的值传递给ax = emner(x)来创建它,但它仅返回:AttributeError:'str'对象没有属性'fagKode',所以我认为我的问题是输入的值创建为字符串,因此不能理解为创建函数的方式
emne=[]
class Emne:
def __init__(self,fagKode):
self.fagKode = fagKode
self.karakter = ""
emne.append(self)
def leggTilEmne():
nyttEmne = input("test:")
nyttEmne=Emne(nyttEmne)
expected result is that the code creates a new instance of the class. 预期结果是代码创建了该类的新实例。
If by choosing a name you mean your fagKode
attribute, what you need is: 如果通过选择名称来表示
fagKode
属性,那么您需要的是:
fagKode = input('Enter code: ')
Emne(fagKode)
You're adding the instances of Enme to the list in the constructor, so you don't need to save them to a variable. 您要将Enme实例添加到构造函数的列表中,因此无需将它们保存到变量中。
Alternatively, you can handle that in the function: 或者,您可以在函数中处理该问题:
emne=[]
class Emne:
def __init__(self,fagKode):
self.fagKode = fagKode
self.karakter = ""
def leggTilEmne():
nyttEmne = input("test:")
enme.append(Emne(nyttEmne))
I'm not sure what exactly you are asking, since you haven't responded to the comments. 我不确定您要问的是什么,因为您尚未回复评论。 So,
所以,
emne=[]
class Emne:
def __init__(self,fagKode):
self.fagKode = fagKode
self.karakter = ""
emne.append(self)
def leggTilEmne(self, value): # <--- is this what you want
self.nyttEmne= Emne(value)
This is an example of when to use a class method. 这是何时使用类方法的示例。
__init__
should not be appending to a global variable, though. __init__
不应附加到全局变量。 Either 1) have the class method append to a class attribute, or 2) have it return the object and let the caller maintain a global list. 1)将class方法附加到class属性上,或者2)使它返回对象,并让调用者维护全局列表。
emne = []
class Emne:
emne = []
def __init__(self, fag_kode):
self.fag_kode = fag_kode
self.karakter = ""
@classmethod
def legg_til_emne_1(cls):
nytt_emne = input("test:")
cls.emne.append(cls(nytt_emne))
@classmethod
def legg_til_emne_2(cls):
nyttEmne = input("test:")
return cls(nyttEmne)
Emne.legg_til_emne_1() # Add to Emne.emne
e = Emne.legg_til_emne_2()
emne.append(e)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.