You're calling the method "platforms" which is not expecting you to pass it a parameter, and are passing it a parameter. The "locations" list is actually passed to the constructor method of your class, which gets called when you instantiate it. Your "platforms" method is called without parameters and prints it.
Here's how you should (probably) do it:
locations = [0,1]
class Draw:
def __init__(self, locations):
self.locations = locations
def platforms(self):
print(self.locations)
draw = Draw(locations)
draw.platforms()
Answer from ag415 on Stack OverflowYou're calling the method "platforms" which is not expecting you to pass it a parameter, and are passing it a parameter. The "locations" list is actually passed to the constructor method of your class, which gets called when you instantiate it. Your "platforms" method is called without parameters and prints it.
Here's how you should (probably) do it:
locations = [0,1]
class Draw:
def __init__(self, locations):
self.locations = locations
def platforms(self):
print(self.locations)
draw = Draw(locations)
draw.platforms()
This could be done with whats called a static method.
locations = [0,1]
class Draw:
def __init__(self, locations):
self.locations = locations
@staticmethod
def platforms(variable):
print(variable)
Draw.platforms(locations)
[0, 1]
python - How Do I Pass One List From A Class To Another Class? - Stack Overflow
python - How can I pass a list from one class to another? - Stack Overflow
python - Trying to pass list of variable in class and function in object oriented manner - Stack Overflow
python - passing list to a function in a class - Stack Overflow
New in Python Please guide
Want to write simple class for Matrix addition using concept of operator overloading
in this line:
def __init__(self,details):
you made the init function take a parameter (details), but here:
pdetails = Mydetails()
you arent giving it a parameter! what you probably wanted to do there is:
pdetails = Mydetails(details)
on a side note your def get_list(self,details): function doesn't make sense, why are you passing it a parameter that doesn't get used?
I fixed my code ,It was error in function def get_list(self,details): changed to def get_details(self): because details parameter already copied in self so it not allow the same thats why throwing error, but below code is fixed and work fine with function calling and defined object also correct from previous code.
CODE
class Mydetails:
__details = '' #protected
def __init__(self,details={}): # constructor
self.__details = details
def set_details(self,details): # function
self.__details = details
def get_details(self):
return self.__details
def toString(self):
return 'Welcome {}'.format(self.__details)
new_details = ['xyz','klm','nop']
pdetails = Mydetails()
pdetails.set_details(new_details)
print(pdetails.get_details())
OUTPUT
['xyz', 'klm', 'nop']
Because fn_one is an instance method, so you're passing strs as self, you can create an instance of Solution for it to be passed as self, and strs to be passed as the strs list:
x = Solution().fn_one(strs)
Output:
ab
Unless this is not what you want, you can define fn_one as a static method using the @staticmethod decorator:
class Solution:
@staticmethod
def fn_one(strs = []): # here, nothing is passed automatically
print(strs[0])
return strs[0]
X = Solution.fn_one(strs)
# Solution().fn_one(strs) would work also, since nothing is passed automatically
Or, as a class method, using the @classmethod decorator:
class Solution:
@classmethod
def fn_one(cls, strs = []): # here, the class is passed automatically as `cls`
print(strs[0])
return strs[0]
X = Solution.fn_one(strs)
But if neither the class nor an object is necessary for the method to work properly, using a static method is the best way to go. And if your class doesn't have any methods in it that work with objects, then a class isn't necessary, just use a function instead.
Add a @classmethod decorator above the fn_one method or instantiate the class first like so: x = Solution().fn_one(strs)
As of late, I’ve been playing around a lot with BeautifulSoup. I find that anytime I call ‘find_all()’ having to loop through the elements to ‘.prettify()’ I let out a sigh. I figured I’d give writing a simple package a shot which would apply ‘.prettify()’ to the list elements and print. My goal is to have this method applied without having to instantiate the class.
For example:
import custom_prettify as purrty
# etc etc…
tables = soup.find_all('table')
#call method
tables.purrty()
# output:
# [list of prettify() html tables]
That []-default-value thing catches a lot of people out, so I'll cover it first. When Python's running your code, it does this:
def append_two(a=[]): a.append(2) return a print(append_two()) print(append_two([1, 2, 3]) print(append_two())Oh, look! A function definition! Ok, so the default value is
[]; let's evaluate that... And some code, but let's not run that yet.def append_two(a=<list object at 0x34FE2910>): ... print(append_two()) print(append_two([1, 2, 3]) print(append_two())Ok, now let's run it. Appending
2to[]makes[2], so weprint("[2]"). Appending2to[1, 2, 3]makes[1, 2, 3, 2], so weprint("[1, 2, 3, 2]"). Appending2to[2]makes[2, 2], so weprint("[2, 2]"). And done![2] [1, 2, 3, 2] [2, 2]
Why does this happen? Well, it was that first stage. Python, when evaluating the function, created The Default List for append_two. And that means that, if you don't pass in a list, it'll always append to that one. That list will slowly grow over time, as more 2s keep getting added to it.
The reason for this is consistency. When you run the function, only the stuff inside the function will run. Nowhere inside the function does it say "make a new list", so it doesn't. If you want it to, you have to tell it to, like so:
def append_two(a=None):
if a is None:
a = [] # Make a new list
a.append(2)
return a
This is clunky and annoying, but that's the price you have to pay for consistency. The alternatives are worse.
Now onto your main problem. I'll simplify it slightly.
class DemoClass:
def __getitem__(self, index):
return index
dataset = DemoClass()
style_clms = ["X", "Y"]
print(dataset[style_clms])
This prints ['X', 'Y']. Let's see what dataset["X", "Y"] prints:
>>> print(dataset["X", "Y"])
('X', 'Y')
Ok... This is called a tuple. It's easy enough to convert a list into a tuple:
>>> print(dataset[tuple(style_clms)])
('X', 'Y')
Hooray! We've successfully replicated dataset["X", "Y"] for arbitrary things! :-) This hopefully solves your problem.
Just flatten the list with this:
import itertools
flat_list = list(itertools.chain(*list2d))
or
flat_list = [item for sublist in l for item in sublist]
Just do this-
list_of_shopping_lists = []
for shoping_list in shopping_lists:
list_of_shopping_lists.append(shop_list.ShoppingList(*shoping_list))
Use Python's arguments unpacking:
shopping_lists = [['apple', 'wine', 'napkins'],
['Avocado', 'soda', 'apron'],
['cherry', 'orange juice', 'knife']]
class ShoppingList():
"""This Class provides a way to store shopping lists."""
# Creating constructor
def __init__(self, fruit, drink, obj):
self._fruit = fruit
self._drink = drink
self._object = obj
list_of_shopping_lists = [ShoppingList(*sh_list) for sh_list in shopping_lists]
print(list_of_shopping_lists)
Sample output:
[<__main__.ShoppingList object at 0x000000000420FF60>, <__main__.ShoppingList object at 0x0000000004F74E48>, <__main__.ShoppingList object at 0x0000000004F556D8>]
Also, avoid naming variables/attributes with list or object to prevent conflicts with Python's reserved names
https://docs.python.org/3.4/tutorial/controlflow.html#arbitrary-argument-lists