I want to create two objects of a class. Using these two objects i want to input some numbers into a list which is a member of the class. After inputting data it will display the content of the list. Simple code. But the output was not which i want.
class Demo:
arr = []
n = 0
def __init__(self,s):
self.n=s
def fill(self):
print("Enter elements in array ")
for i in range(self.n):
x=input()
self.arr.append(x)
def show(self):
for i in range(self.n):
print(self.arr[i])
obj1 = Demo(5)
obj2 = Demo(3)
obj1.fill()
obj2.fill()
print("Data from first Object")
obj1.show()
print("Data from second object")
obj2.show()
You should have:
def __init__(self,s):
self.n=s
self.arr = []
By creating arr in the body of the class (rather than in the initializer), it becomes part of the class itself - shared by all instances.
Related
I'm practicing OOP in python and I'm trying to rewrite my code using class. Each instance in the class is meant to have a unique value for a particular instance variable. So I need to check to see if the value that is to be assigned is not being used by another instance before assigning.
So for example, how do i convert something like this using class.
from random import randint
accounts = {}
acc_number = []
names = ['john','ambrose','jess']
for name in names:
acc_num = randint(1,10)
while True:
if acc_num in acc_number:
acc_num = randint(1,10)
else:
acc_number.append(acc_num)
break
accounts[name] = acc_num
print(accounts)
Since the purpose of class is to keep each instance's values apart, how can I neatly ensure acc_numberis unique?
are you talking about how to make a class that's guaranteed to have a unique attribute named acc_num?
used_acc_nums = []
class Account:
def __init__(self,name):
self.name = name
self.acc_num = random.randint(0,10)
while self.acc_num in used_acc_nums:
self.acc_num = random.randint(0,10)
used_acc_nums.append(self.acc_num)
john = Account("John")
ambrose = Account("Ambrose")
jess = Account("Jess")
for acc in [john, ambrose,jess]:
print(acc.name , acc.acc_num)
Could have something like this:
from random import choice
class Person:
def __init__(self):
self.id = list(range(1, 10))
self.accounts = {}
def assign(self, name):
get_id = choice(self.id)
self.id.remove(get_id)
self.accounts[name] = get_id
def accounts(self):
return self.accounts
person = Person()
people = ['john', 'ambrose', 'jess']
for p in people:
person.assign(p)
print(person.accounts)
>>> {'john': 6, 'ambrose': 8, 'jess': 7}
I'm facing problem with my code. In fact, I need to create a list of instances of my class( Patent). The name of the list is patent_ints. But when I'm trying to verify if any element in that list is a Patent one, I'm always getting a False response. And when iterating the first element is like "<__main__.Patent at 0x7f107820b710>".
Here is my code, I need help !
import json
import datetime
patent_data = json.loads(open('NASA_data.json', "r").read())
unique_center = []
for thing in patent_data["Patent_Information"]["Results"]:
for val in thing:
if(val == 'NASA Center'):
unique_center.append(thing[val])
total_num_centers = len(set(unique_center))
class Patent:
def __init__(self, abbreviated_organization_name, dict_data):
self.org_name = abbreviated_organization_name
self.title = dict_data["Title"]
# initialize instance variable called year. The value can be extracted from dict_data.
# This should be a four digit string.
self.year = str(datetime.datetime.strptime(dict_data['Date'], '%m/%d/%Y').year) #dict_data['Date'].split('/')[2]
# initialize an instance variable called month. The value can be extracted from dict_data.
# This should be a two digit string.
self.month = str(datetime.datetime.strptime(dict_data['Date'], '%m/%d/%Y').month) #dict_data['Date'].split('/')[0]
# initialize an instance variable called day. The value can be extracted from dict_data.
# This should be a two digit string.
self.day = str(datetime.datetime.strptime(dict_data['Date'], '%m/%d/%Y').day) #dict_data['Date'].split('/')[1]
self.id = dict_data['Case Number']
self.access_limit = dict_data['SRA Final']
patent_ints = [Patent(i, data) for i in unique_center for data in patent_data["Patent_Information"]["Results"]]
patent_ints[0]
Thank you in advance!
<__main__.Patent at 0x7f107820b710> is the default representation of the class when you try to print it. Add an __str__ or __repr__ method to the class and define some custom logic to return your desired details as a string:
class Patent:
def __init__(self, abbreviated_organization_name, dict_data):
...
def __repr__(self):
# return a dictionary of items in the class but you can return whatever you want
# you could do f'{self.title} {self.id} {self.year}-{self.month}-{self.day}' but str(self.__dict__) is quick to test
return str(self.__dict__)
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 a x = 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)
i have the following problem in python. I declare a class element with some property and a class network with a list population.
Now I populate the network with objects of class element: e1,e2 and e3. When I try to get the properties of the elements populating the network, I get an error.
Can you pls help me understanding the issues?
import sys
class element:
def __init__(self):
self.property = 1
def getProperty(self):
return(self.property)
class network:
def __init__(self):
self.population = []
def addElement(self, element):
self.population.append([element])
def getElementProp(self):
for i in range(0, len(self.population)):
#print(self.population[i])
print(self.population[i].getProperty())
print(sys.version_info)
e1 = element()
e2 = element()
e3 = element()
net = network()
net.addElement(e1)
net.addElement(e2)
net.addElement(e3)
net.getElementProp()
**Output:**
line 20, in getElementProp
print((self.population[i]).getProperty())
AttributeError: 'list' object has no attribute 'getProperty
You are appending a list object containing an element instance while you should be appending the instance directly to your population list:
def addElement(self, element):
self.population.append(element)
You could also expand your method to take one or more elements at the same time, without the need to make repeated calls:
def addElements(self, *elements):
self.population.extend(elements)
...
net = network()
net.addElements(e1, e2, e3)
More so, in your getElementProp method, it is more Pythonic to iterate on the elements directly rather than use range(len(...)) with a later list indexing:
def getElementProp(self):
for e in self.population:
print(e.getProperty())
Write a class and implement a list using embedded python list.
Input like : 4 9 3 5
Output should be like: 3 4 5 9
I use this code for taking the input values and split it to the list
s = input()
numbers = map(int, s.split())
How can i build up a class for this listPQ that takes the lists values and put, get and check if the list is empty?
To try if your queue works:
q = ListPQ()
q.put(3)
q.put(4)
x = q.get()
y = q.get()
print(x,y) #it should print 3 4
class ListPQ():
def __init__(self):
self.pq = []
def put(self, val):
# Write code to put the number and keep it in sorted way, however you decide to
# you can use self.pq to access the list and add stuff to it... this instance
# of the class will have it saved.
self.pq.append(val)
self.pq.sort() # This is just for brevity, you can use your own algo for this
def get(self):
# likewise, use the self.pq to pop it out like,
return self.pq.pop(-1)
def is_empty(self):
return len(self.pq) == 0
def __repr__(self):
return "<ListPQ: %r>" % self.pq
Now you can go ahead and use print(instance_of_listpq) and this will print out the list as it's written in the __repr__ method.
Hope this helps now!
You could use the heapq module from the python standard library. Then it is even possible without a class.
Without class:
import heapq
h = []
heapq.heappush(h, 4)
heapq.heappush(h, 3)
heapq.heappush(h, 9)
heapq.heappush(h, 5)
print(heapq.heappop(h))
print(heapq.heappop(h))
print(heapq.heappop(h))
print(heapq.heappop(h))
the output would be (space instead of newline):
3 4 9 5
If you need a class you can do it as follows:
class ListPQ():
def __init__(self):
self.h = []
def put(self, item):
heapq.heappush(self.h, item)
def get(self):
return heapq.heappop(self.h)