How to initiate the contents of a subclassed UserList in Python [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
This works:
class customList(list):
def __init__(self, liste):
list.__init__(self, liste)
myList = customList([4])
This does not:
from collections import UserList
class customList(UserList):
def __init__(self, liste):
list.__init__(self, liste)
myList = customList([4])
I have read subclassing UserList is preferred over subclassing the build-in list, because of unknown behavior of the latter, but how should I initiate the list in my __init__ when subclassing from UserList?

You should use UserList's constructor to initialize it, instead of list's constructor:
class customList(UserList):
def __init__(self, liste):
super().__init__(liste)

A UserList is a wrapper around its internal data parameter.
from collections import UserList
class customList(UserList):
def __init__(self, liste):
self.data = liste
myList = customList([4])
print(myList) # [4]
myList.append(5)
print(myList) # [4, 5]
The main reason you might want to use a UserList rather than a list as your base class is to access the underlying list as an attribute, which is only really important if you wanted to reassign it for some reason.

Related

Creating a Class and Objects [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I got an assignment. I have to create a class with objects. For example, the class Student. In this class I have to create certain students and then I have to assign these students to a set.
class Students:
def __init__(self, name, age):
self.name = name
self.age = age
def show_info(self):
return "'{}': {}".format(self.name, self.age)
def __str__(self):
return self.show_info()
Mark = Students(name="Mark", age=21)
Lisa = Students(name="Lisa", age=19)
So my question is how do I add these Objects(Mark,Lisa) to a set(). I'd be grateful if someone can give me some hints.
Assuming you want the class instances Mark and Lisa themselves to be added to a set, a simple way in Python 3 is to make use of dataclasses -- which are essentially just regular classes under the hood -- and pass the unsafe_hash parameter to the decorator, so that a __hash__ method is automatically generated for us, as shown below.
from dataclasses import dataclass
#dataclass(unsafe_hash=True)
class Student:
name: str
age: int
def show_info(self):
return "'{}': {}".format(self.name, self.age)
def __str__(self):
return self.show_info()
Mark = Student(name="Mark", age=21)
Lisa = Student(name="Lisa", age=19)
my_set = {Mark, Lisa}
print(my_set)
# If you want to customize how `Student` objects are displayed, implement
# a __repr__ instead of __str__, or just copy the implementation directly.
Student.__repr__ = Student.__str__
print(my_set)
Output:
{Student(name='Lisa', age=19), Student(name='Mark', age=21)}
{'Lisa': 19, 'Mark': 21}
If you want to add the instances attributes to a set instead, you can convert each instance to a tuple of its attributes and pass it into the set constructor instead, since tuples are immutable objects and are thus hashable. This is actually a great use-case for the astuple helper function which is exported by the dataclasses module.
from dataclasses import dataclass, astuple
#dataclass
class Student:
name: str
age: int
Mark = Student(name="Mark", age=21)
Lisa = Student(name="Lisa", age=19)
my_set = {astuple(Mark), astuple(Lisa)}
print(my_set)
Output:
{('Lisa', 19), ('Mark', 21)}
A simplification of the above concept is to use typing.NamedTuple instead of the dataclass approach. This allows you to retain the type hinting support and the ability to pass keyword arguments to the constructor method as in the original example, but also makes each class instance inherently hashable, since named tuples are essentially tuples under the hood. An example usage of NamedTuple is shown below:
from typing import NamedTuple
class Student(NamedTuple):
name: str
age: int
Mark = Student(name="Mark", age=21)
Lisa = Student(name="Lisa", age=19)
my_set = {Mark, Lisa}
print(my_set)
Output:
{Student(name='Lisa', age=19), Student(name='Mark', age=21)}

Best practice to create a python class that manage an object list and how to include in UML diagram [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I am trying to improve my object oriented programming skills. So I did this practice in python in which I try to create a cake object. However I have a doubt as to whether I am doing things correctly.
I need this class handle a list of ingredients.For this I created an empty list and a method that receives as a parameter an Ingredent object instance.
#Define a ingredient.
class Ingredient:
#Constructor of ingredient
def __init__(self, name,measure):
#Name of ingredient
self.name = name
#unit of measurement
self.measure = measure
class IngredientQuantity(Ingredient):
def __init__(self,name,measure,quantity):
'''
Here we are having access to methods and attributes from
the parent class. Now we can set attribute values and access to
methods.
'''
super().__init__(name,measure)
#Define quantity of ingredient.
self.quantity = quantity
#Define a list of ingredients.
class IngredentsList:
def __init__(self):
#Empty list that will be populated with ingredients.
self.listOfIngredients = []
#Add a new ingredient to list.
def addIngredent(self,ingredient):
print('adding ' + str(ingredient.quantity) + ' ' + ingredient.measure + ' of ' + ingredient.name + '...')
self.listOfIngredients.append(ingredient)
Here is how I pass parameters...
ilist = IngredentsList()
ilist.addIngredent(IngredientQuantity('ingredient','piece',1))
I'm not sure this is the best way to do it. Then I would like to hear an opinion.
I also have doubts about how to treat this class in a UML diagram. This class is not inherited from any other. How could I relate it?
Thanks in advance.
An ingredient is just a string. Doesn't need a class.
A measurement, on the otherhand includes a unit and a quantity (e.g. 2 TBSP). So, create a class for that
from dataclasses import dataclass
#dataclass
class Measurement:
unit: str
quantity: float
Then you want to store a list of ingredients with measurements, so you can use a list of tuples
recipe = [
('Apples', Measurement(None, 1.0))
('Cinnamon', Measurement('tbsp', 2.0))
]
If you really wanted to create other classes, you could, but the relationships as far as UML goes is composition and aggregation, not inheritance.

How to change value dict out class [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I want to change dict value, but allert me a Error 'object does not support item assignment'
Full Code:
def __init__(self):
self.dict = dict()
def __getitem__(self, item):
return self.dict[item]
arr = SparseArray()
arr[0] = 1```
You to override __setitem__
def __setitem__(self, key, value):
self.dict[key] = value
Then you'll be able to assign a value using an index
# use of __setitem__
arr[0] = 1
arr["foo"] = 5
# use of __getitem__
print(arr[0]) # 1
print(arr["foo"]) # 5
Also avoid naming variable as built-in name like dict, at least you can use items or values if there is no real sense about the variable's content

Accessing Methods of a class using function parameter in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have a class like this in python:
class xyz:
def abc():
#Do Something
def add(x,y):
#Add x and y
def sub(x,y):
#Subtract y from x
def mul(x,y):
#multiply x ynd y
Note: Here "add", "sub" and "mul" are nested methods.
Is it allowed to make a class like this?
If it is allowed, then i want to access the methods "add", "sub" and "mul" by function parameters. for e.g.:
from xyz import xyz
def jkl(input):
abc.(input) # By doing this it will raise syntax error. This is just for refernece.
so, when i call jkl(add(2,3)) it should add the numbers. Similarly when i call jkl(sub(4,3)) it should subtract the numbers.
Can it be done?
It's hard to understand exactly what your goal is here.
EDIT: I'll leave this answer here since it has received an upvote, but OP clarified that they're actually asking how to overload operators.
You can do this:
class abc():
//Do Something
#staticmethod
def add(x,y):
# Add x and y
#staticmethod
def sub(x,y):
# Subtract y from x
#staticmethod
def mul(x,y):
# multiply x ynd y
abc.add(1,1)
If you want to use your class in another module, you can put that class definition in file xyz.py, and then in another file (in the same directory):
from xyz import abc
abc.add(1,1)
However, this is a very odd thing to do in the Python world. I'd advise organizing things differently, unless you have a really good reason to do things this way. A better way would be to skip the class definition altogether, and do this in abc.py:
def add(x,y):
# Add x and y
def sub(x,y):
# Subtract y from x
def mul(x,y):
# multiply x ynd y
Then import from that module:
import abc
abc.add(1,1)
etc...
Alternatively, you can do this:
from abc import add, sub, mul
add(1,1)
etc...

Is it possible to specify attribute names when creating an instance of namedtuple? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
To create and use named tuple in Python, generally it's like this:
MyTuple = namedtuple('MyTuple', ['attr1', 'attr2', 'attr3'])
new_tuple = MyTuple('Bob', 'John', 'Tom')
Is there a way to specify attributes when creating the instance?
For example, I'd like to do something like:
new_tuple = MyTuple(attr1='Bob', attr2='John', attr3='Tom') # this does NOT work.
The only goal of this is to add readability in my code.
Thank you.
This will technically work and is semi-self-documenting:
new_tuple = namedtuple('MyTuple', ['attr1', 'attr2', 'attr3'])('Bob', 'John', 'Tom')
Of course, you're creating a new class each time, which is inefficient. So you could write a helper function to do it with keywords as you want:
def nt_from_kws(cls, **kw):
return cls(*(kw[k] for k in cls._fields))
Usage:
MyTuple = namedtuple('MyTuple', ['attr1', 'attr2', 'attr3'])
new_tuple = nt_from_kws(MyTuple, attr1=1, attr2=2, attr3=3)
For even more fun, write a substitute namedtuple factory that adds a from_kws classmethod to the generated class:
from collections import namedtuple
#classmethod
def from_kws(cls, **kw):
return cls(*(kw[k] for k in cls._fields))
def namedtuple(name, fields, namedtuple=namedtuple):
nt = namedtuple(name, fields)
nt.from_kws = from_kws
return nt
Usage:
MyTuple = namedtuple('MyTuple', ['attr1', 'attr2', 'attr3'])
new_tuple = MyTuple.from_kws(attr1=1, attr2=2, attr3=3)

Categories

Resources