python: how list increase in a object [duplicate] - python

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

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

Python OOP, Class and Instance [duplicate]

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')

How can I print the value of the list element that storing/referencing the address/location? [duplicate]

This question already has answers here:
How to print instances of a class using print()?
(12 answers)
Why is `print(object)` displaying `<__main__. object at 0x02C08790>`?
(5 answers)
Closed 1 year ago.
class Mobile:
def __init__(self,brand,price):
self.brand = brand
self.price = price
mob1=Mobile("Apple", 1000)
mob2=Mobile("Samsung", 5000)
mob3=Mobile("Apple", 3000)
mob_dict = {
"m1":mob1,
"m2":mob2,
"m3":mob3
}
lit = []
for key,value in mob_dict.items():
if value.price > 3000:
lit.append(value)
print (value.brand,value.price)
print(lit)
Output:
[<__main__.Mobile object at 0x000001C45C721100>]
Please explain why am getting this output.
You are printing the whole object, you can do print(lit[0]) or:
for elem in lit:
print(elem)

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.

Calling out a function, not defined error [duplicate]

This question already has answers here:
How can I call a function within a class?
(2 answers)
Closed 3 years ago.
I'm new to making classes and I'm trying to complete exercise 9-1 in my 'Python Crash Course' book where the last part of the question asks me to call back my method but I end up getting
'not defined error' for describe_restaurant().
Here is my code:
class Restaurant():
def __init__(self, r_name, c_type):
self.r_name = r_name
self.c_type = c_type
def describe_restaurant():
print(self.r_name.title())
print(self.c_type.title())
def open_restaurant():
print(self.r_name + " is now open!")
Restaurant = Restaurant('Joe\'s Sushi', 'sushi')
print(Restaurant.r_name)
print(Restaurant.c_type)
describe_restaurant()
open_restaurant()
I thought that describe_restaurant shouldn't need to be defined though because I'm calling it out as a function to use?
Try:
class Restaurant():
def __init__(self, r_name, c_type):
self.r_name = r_name
self.c_type = c_type
def describe_restaurant(self):
print(self.r_name)
print(self.c_type)
def open_restaurant(self):
return "{} is now open!".format(self.r_name)
restaurant = Restaurant('Joe\'s Sushi', 'sushi')
print(restaurant.r_name)
print(restaurant.c_type)
restaurant.describe_restaurant()
restaurant.open_restaurant()
You need to create a class instance and call it's functions. In addition, as mentioned in the comments, you need to pass self to the instance methods. A short explanation of this can be found here.

Categories

Resources