Python OOP, Class and Instance [duplicate] - python

This question already has answers here:
How to avoid having class data shared among instances?
(7 answers)
Closed 1 year ago.
I'm currently learning Python in OOP,
I have a question about using list as a class attribute. The question is when I change something in objects it will also change that class attribute.
class Backet:
number_of_stone = 0
stone_collection = []
def __init__(self,name):
self.name = name
self.number_of_stone +=1
self.stone_collection.append(self.name)
stone_one = Backet('One')
stone_two = Backet('Two')
When I print out the stone_one and stone_two.number_of_two they are = 1 (I know this is correct). But when I print stone_one and stone_two.stone_collection they both give a list ["One","Two"].
My question is that should it be stone_one.stone_collection = ['One'] and stone_two.stone_collection = ['Two']

Change stone_collection to instance variable:
class Backet:
def __init__(self, name):
number_of_stone = 0
stone_collection = []
self.name = name
self.number_of_stone +=1
self.stone_collection.append(self.name)
stone_one = Backet('One')
stone_two = Backet('Two')

Related

How to print list of all class instances with their values instead of location in memory? [duplicate]

This question already has answers here:
How to print instances of a class using print()?
(12 answers)
Printing a list of objects of user defined class
(3 answers)
Closed 11 months ago.
I met that problem before while studying the OOP and lack experience for sure. Surfed through a lot of stackoverflow pages but somehow all suggestions do not help. Please, refer me to the appropriate resources or give some hint if possible. Thanks in advance!
class Student:
students = []
def __init__(self, name, money):
self.name = name
self.money = money
self.students.append(self)
#classmethod
def mostMoney(cls):
all_money = [elt.money for elt in cls.students]
if all(element == all_money[0] for element in all_money) == True:
return cls.students
else:
for student in cls.students:
max_money = student.money
current_name = student.name
if student.money >= max(all_money):
return max_money, current_name
else:
continue
student_1 = Student('Stas', 800)
student_2 = Student('Yarik', 800)
student_3 = Student('Kris', 800)
print(Student.mostMoney())
The idea to return all students if they have equal value in money.
Here is the return I get.
[<__main__.Student object at 0x7f7ae679e130>, <__main__.Student object at 0x7f7ae66c2070>, <__main__.Student object at 0x7f7ae66c22e0>]

Create 100 Participants in a class without declaring them one by one [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 11 months ago.
My plan is to allocate 100 Participants with random attributes to a class.
What is the best way to do that without having to declare them one by one like this:
p1 = Participant()
p2 = Participant()
p3 = Participant() etc.
Class definition:
import names
import random
status_list = ["single", "married", "widowed", "complicated"]
class Paricipant():
def __init__(self, name= None, age = None, status = None):
if name is None:
self.name = names.get_first_name()
if age is None:
self.age = random.randint(22, 50)
if status is None:
self.status = random.choice(status_list)
def return_all(self):
print(self.name)
print(self.age)
print(self.status)
You can store them in a list. There are two ways to create the list:
First, you can use a list comprehension:
participants = [Paricipant() for _ in range(100)]
Alternatively, if you don't like list comprehensions, you can use a for loop instead:
participants = []
for _ in range(100):
participants.append(Paricipant())
I also think you misspelled "Participant" (the class name is currently "Paricipant").

Class with dictionary not getting initialized [duplicate]

This question already has answers here:
How to avoid having class data shared among instances?
(7 answers)
Closed 5 years ago.
I have a simple class with a string and a dictionary. When I make multiple objects of the class, apparently the dictionary does not get initialized properly. Dictionaries of all objects contains the entry for last object created. The code is:
# a simple class with a string and a dictionary:
class Myclass:
name = ""
valuedict = {}
# a list for objects:
mylist = []
# create 3 objects:
for i in range(3):
mc = Myclass()
mc.name = str(i)
mc.valuedict['name'] = str(i)
mylist.append(mc)
# disply objects in list:
for item in mylist:
print("-----------------")
print("name = ", item.name)
print("name in dict = ", item.valuedict['name'])
The output is:
-----------------
name = 0
name in dict = 2
-----------------
name = 1
name in dict = 2
-----------------
name = 2
name in dict = 2
The name strings are 0, 1 and 2 as expected but name in dictionary is 2 in all 3 objects. Where is the problem and how can it be solved? Thanks for your help.
Currently, valuedict is a class object. I believe what you're going for is to have separate instances, in which case you'll need a constructor (called __init__ in Python).
The corrected class code is as follows (self refers to the instance of the class)
class Myclass:
def __init__(self):
self.name = ""
self.valuedict = {}
So why isn't name acting the same way? In the first for loop, you're defining name, where you're accessing a key of valuedict, which doesn't exist, so you take the "next best thing", the class variable. name doesn't have this problem, as you're initializing it. A better explanation of this can be found here.

python: how list increase in a object [duplicate]

This question already has answers here:
How to avoid having class data shared among instances?
(7 answers)
Should I use instance or class attributes if there will only be one instance? [closed]
(4 answers)
Closed 7 years ago.
Could you help me to find the problems?
I just add the object to one list, but it seems that it appears in another list!
class people(object):
name = ""
__adjacent = []
position = 0
def __init__(self,nam):
self.name = nam
def print_name(self):
print self.name
def get_adjacent(self):
return self.__adjacent
def append_adjacent(self,people):
self.__adjacent.append(people)
sis = people('sister')
bro = people('brother')
sis.append_adjacent(bro)
print len(bro.get_adjacent())
for i in bro.get_adjacent():
i.print_name()
print len(sis.get_adjacent())
Question: why there is a object in bro's adjacent list???

List of python objects, each with their own dictionary of arrays. Appending to one appends to all [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
dictionary shared between objects for no reason?
class Player():
zones = {}
def __init__(self):
self.zones['hand'] = []
def InitHand(self):
for a in range(5):
self.zones['hand'].append(a)
lst = []
lst.append(Player())
lst.append(Player())
lst[0].InitHand()
print lst[1].zones['hand']
This prints "[0, 1, 2, 3, 4]", but I only initialized the 0th element...
Changing them to arrays as below fixes the problem, but for the life of me I can't figure out why this happens.
class Player2():
zones = []
def __init__(self):
self.zones = []
def InitHand(self):
for a in range(5):
self.zones.append(a)
lst = []
lst.append(Player2())
lst.append(Player2())
lst[0].InitHand()
print lst[1].zones
This prints "[]" as expected
In your code, all players share the same zones dictionary. Anything set in the class scope is a class attribute, not an instance attribute.
class Player():
def __init__(self):
self.zones = {}
self.zones['hand'] = []
def InitHand(self):
for a in range(5):
self.zones['hand'].append(a)

Categories

Resources