简体   繁体   中英

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. 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

 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 = 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.

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. 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.

 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM