i am learning python by myself. Right now i try to code a address book. I read that you should use a class for it and i don't get why because you could define every function you have in this class (like insertaddress, deletaddres,... ) without one and use it like normal functions. Or am i wrong?
But to get some practice with classes i created one:
class Addressbook():
def __init__(self,last,first,street,num,plz,place):
self.last=last
self.first=first
self.street=street
self.num=num
self.plz=plz
self.place=place
def insertadd(self):
text =self.last+" "+self.first+" "+self.street+"
"+self.num+" "+self.plz+" "+self.place+"\n"
with open("addressbook.txt", "a") as file:
file.write(text)
In my main-file:
from klassen import Addressbook
k.last= input()
k.first=input()
(...)
k.place = input()
k.insertadd()
But when i import my class via from klassen import Addressbook as k
and link the class attributes to my input: k.first=input("text")
and try to execute the function k.insertadd()
i get an errror message.
NameError: name 'self' is not defined
When i give my function every paramter i have as an input i get an error which tells me that "place" is a missing paramter.
Could you please help me?
You should do:
from klassen import Addressbook
k = Addressbook("","","","","","") # Init it with the variables you want!
Then you can use k as an object...
The way you were doing, you were not creating a instance of an Addressbook object, you were using the class object itself...