Iterate over python class - python

I am learning how to do OOP with python. I would like to create a class B that contains an array/list of classA and execute a function in a for loop.
Here is an example:
class A:
def __init__(self, name):
self.name = name
def printSomething(self):
print (self.name)
class B:
def __init__(self, listOfNames):
# struture to store a list of objects A based on the list of names supplied
def printSomething2(self):
for i in # struture to store a list of objects A based on the list of names supplied :
i.printSomething()
names = ["a,b,c,d"]
obj = B(names)
obj.printSomething2()
what python structure is suitable for storing multiple objects? How can I set the size of it based on the input of the class?
For can I iterate over the created structure to call a function?
Best Regards

You could just use:
class B():
def __init__(self,listOfNames):
self.name_objs = []
for name in listOfNames:
self.name_objs.append(A(name))
def printSomething2(self):
for i in self.name_objs:
i.printSomething()
Still this is dynamic and getting the size to set this before is rather hard but this would work

Related

Python initialize variables with default data for multiple objects

I want to initialize variables with default values in a constructor without parameters, like this:
class Persons()
def __init__(self):
self.name="Joan"
p1=Persons()
print(p1.name)
So the result for this, will be "Joan". It will print the name of the person. All good. But how do I do this for multiple objects? I want to print p2.name, p3.name, with different names, just like above.
I got this from an exercise that asks me to "create a constructor without parameters that initializes variables with default data".
Just add name as a parameter:
class Persons()
def __init__(self, name):
self.name = name
p1=Persons(“Joan”)
print(p1.name)
Or
p1.name = “Jim”
If your class can provide a set of possible names, you can create an object from which each call to Person.__init__ gets a different name. For example:
from itertools import cycle
class Person:
names = cycle(["Alice", "Bob", "Carol", "Dan"])
def __init__(self):
self.name = next(Person.names)
Add as many names to the pool as desired.
Names will necessarily repeat once the initial set of names is exhausted and the cycle begins again. With a little more work, we can at least vary the order in which names are produced on each cycle:
from itertools import cycle
import random
class Person:
def shuffled_cycle(names):
while True:
random.shuffle(names)
yield from names
names = shuffled_cycle(["Alice", "Bob", "Carol", "Dan"])
def __init__(self):
self.name = next(Person.names)
Of course, if repeated names aren't a concern, just call random.choice from inside __init__. This is much simpler:
import random
class Person:
def __init__(self):
self.name = random.choice(["Alice", "Bob", "Carol", "Dan"])
Taken to its extreme, just generate random names from a primordial soup of letters:
import random
import string
class Person:
def __init__(self):
k = random.randint(3, 10)
self.name = ''.join(random.sample(string.ascii_lowercase, k)).title()
So the thing is you want to initialize with default values, The code you wrote is correct.Every new instance of "Person" class will initialize with the same default value which is good coding practice.Since it is "default" value thus same. However for the sake of knowledge I have written a small program that can give new names to 5 new instances of class Person however do not use this in production as it is a bad practice but good for learning.
class Person :
#class Variable
name_list=["Jhon","Naruto","James","Smith","Neo"]
instance_count = 0
def __init__(self):
#Resets instance count when instances become greater that 5
instance_count = instance_count%5
#Sets new name
self.name = name_list[instance_count]
#increment instance_count
instance_count = instance_count + 1

Can we create a dictionary in member functions from the class variables in python?

I have a class which initializes variables from a dictionary parameter. And the member function of this class in-turn has to access a dictionary with "keys" as class variables and "values" as the values, that those variables are initialized with. To illustrate I have taken a simple example to explain the context:
I can do that using vars(class instance) but is there any other way to do that ?
# my_dict with variable number of keys
my_dict = {"v1" : "23.5", "v2" : "54.6", "v3" : "67.8" }
class Area(object):
def __init__(self, my_dict):
self.length = my_dict.get("v1")
self.bre = my_dict.get("v2")
self.height = my_dict.get("v3")
self.width = my_dict.get("v4") ## which should return None
def calculate(self):
## I want to access the class variables as a dictionary here
area_instance = Area(my_dict)
area_dict = vars(area_instance)
# do calculation using area_dict by iterating over the dict
return calculated value
a = Area(my_dict)
print (a.calculate)
I am looking for Pythonic way to access class variables as a dictionary without creating
that class instance.
If you want to access a class (and it's attributes) try putting before the function #classmethod. this will make so that the first argument of the function is considered as the class. Hope it helps

How to create a python class with list variable

How to write a class that makes
an list for each instance. I am
concerned on the class part.
I know how to make a int , double
or string, but I need an list
(string).
The list will have later values
assigned to it, when it is an
instance and there will be
custom methods in the class
for the objects/instances.
Classes in Python can have their member variables instantiated within the __init__ function, which is called upon creation of the class object. You should read up on classes here if you are unfamiliar with how to create one. Here is an example class that instantiates a list as a member and allows appending to the list:
class ListContainer:
def __init__(self):
self.internal_list = [] # list member variable, unique to each instantiated class
def append(elem):
self.internal_list.append(elem)
def getList():
return self.internal_list
list_container_1 = ListContainer()
list_container_1.append('example')
print list_container_1.getList() # prints ['example']
list_container_2 = ListContainer()
print list_container_2.getList() # prints []

How to make dictionary element an object in python?

How to make dictionary element an object in Python?
I made a class…
class Qs:
def __init__(self,list1,id,quest="",mark=1):
self.__list1=list1
self.__id=id
self.__quest=quest
self.__mark=mark
self.__list1.update({self.__id:{self.__quest:self.__mark}})
How can I store objects in a dictionary so I can call functions in this class like this?
dictionary[1].print()
what you probably want is another class that includes a dictionary in it:
class QuestionCollection:
def __init__(self):
self.listofquestions = dict()
def print(self,question_number):
print(dictionary[question_number])
Then you could do this:
classobject = MyClass()
classobject.listofquestions[1] = Qs(...)
classobject.print(1)
or,
classobject = MyClass()
print(classobject.dictionary[1])
Then, you could extend this class to include other functions that operate on your entire dictionary.

Adding elements to a set , adds elements to all the instances of the object containing this set

Hi
I have created a List of Objects. Each object contains a Set. I want to update the set's contents for all the objects in the list. The code that i wrote to accomplish this is
class Player:
name = ""
cardsInHand = set()
hasBid = False
def __init__(self, name):
self.name = name
class CardDeck:
deck = []
def __init__(self):
for i in range(39) :
if i%10>0 and i%10<9 :
self.deck.append(i)
def dealCards(self,player):
cardIndex = 0
for tempPlayer in player:
for j in range(4): # since want to add four elements at a time
tempPlayer.cardsInHand.add(self.deck.pop(cardIndex))
cardIndex = cardIndex +1
in the main method I am calling the above classes with the following code
players = []
players.append(Player("Player0"))
players.append(Player("Player1"))
players.append(Player("Player2"))
players.append(Player("Player3"))
cards.dealCards(players)
The problem is that dealCards method adds the elements to all the sets of objects. Instead of 4 elements in each object's set, I endup with same 16 elements in each objects's set?
I am new to python, am i doing something wrong ?
You're creating class attributes.
class Player:
def __init__(self, name):
self.name = name
self.cardsInHand = set()
self.hasBid = False
You've defined cardsInHand (as well as name and hasBid) to be class variables instead of instance variables; by defining them in the class body, you're defining them to be variables shared by all instances. If you're familiar with Java, they are essentially like static variables. To make them instance variables, you need to declare them in the __init__ method, like so:
def __init__(self, name):
self.name = name
self.hasBid = False
self.cardsInHand = set()

Categories

Resources