logo
Tags down

shadow

python: Beginner doesn't understand outcome: appending a list with a class


By : StillatLarge
Date : July 30 2020, 01:00 PM
I wish this help you __str__ is only used when you print objects, you can use __repr__ to get a convenient "representation" on the console (more details):
code :
>>> class av:
...     def __init__(self, num):
...         self.num = num
...     def __str__(self):
...         return str(self.num)
...     def __repr__(self):
...         return 'av(%d)' % self.num
... 
>>> av(12)
av(12)
>>> print(av(12))
12
>>> [av(12), av(12)]
[av(12), av(12)]
>>> print([av(12), av(12)])
[av(12), av(12)]


Share : facebook icon twitter icon

Some beginner error I don't understand in python


By : Marcus Sandy
Date : March 29 2020, 07:55 AM
this one helps. In Python 3, print is a function, so this code calls print("%s + %s + %s") and then applies % to the result of that call, which is None.
Try print ("%s + %s + %s" % (now.year, now.month, now.day))

Python: Appending elements to list of a class


By : user3662519
Date : March 29 2020, 07:55 AM
wish of those help I have a class that looks like this , You may want to use a subclass here:
code :
class Someclass1(Someclass):
    field = Someclass.field + [XShortField("Field"+str(option), 0x2000]

s_class = Someclass
if option == 0: #nothing is added
    pass
elif option == 1: #one element is added
    s_class = Someclass1
elif option == 2: #two elements are added
    [...]
    #and so on

appending a class to list results in appending str error python


By : Nnnnikkkii
Date : March 29 2020, 07:55 AM
I wish this helpful for you So I my program has a class with a persons name. I am trying to have the program read it off from a input file and then read it and arrange it into classes. While I am trying to appened the class to a list. It gives me this error: AttributeError: 'str' object has no attribute 'append' I have used this code before to do the same similar thing, but without reading from a file. I was wondering what was happening to cause this error. Here is my code: , Few issues in your code -
code :
classlist = []
while i != -1:
  try:
    z=lines[i]
    a=lines[i+1]
    r=lines[i+2]
    i = i + 3
    hi=person(z,a,r)
    classlist.append(hi)
except IndexError:
    i = -1

Python beginner trying to understand how to run input() function


By : Martijn Benjamin
Date : March 29 2020, 07:55 AM
will help you It's a bit unclear what you've done, and those "> >" are a bit odd to me, usually python has 3 ">" when you execute it.
The input function in python stops the execution and waits until the user types something (or nothing) and presses the return key (enter). You can assign whatever the user inputed from his keyboard into a variable, as you did.
code :
variable = input("Some text to show the user what he should do")
# Execution will stop until user presses enter
print(variable)  # Will print whatever the user typed when the above text was printed to him.

Python class objects appending to list


By : alexu4der
Date : March 29 2020, 07:55 AM
will help you As pointed by others in comments.In your code at the moment you are getting the expected result as r and r1 are the instances of the class. In case you want to differentiate your instances on the basis of name and want to return the same you can pass name argument and define __repr__ to represent your output when str(instance) is being called. Just giving you a heads up:
code :
class Robot():
    """Test class"""
    def __init__(self, age, name):
        self.age = age
        self.name = name

    def __repr__(self):
        return self.name

r = Robot(10,'r')
r1 = Robot(15,'r1')

mylist1 = [r, r1]
mylist2 = []

for item in mylist1:
    mylist2.append(item)
print(mylist2)
[r, r1]
class Robot():
    """Test class"""
    def __init__(self, age,name):
        self.age = age
        self.name=name

r = Robot(10,'r')
r1 = Robot(15,'r1')

mylist1 = [r, r1]
d={}

for item in mylist1:
    d[item.name]=item
print(d)
{'r': <__main__.Robot instance at 0x0000000010BAD708>, 'r1': <__main__.Robot instance at 0x0000000010BAD148>}
Related Posts Related Posts :
  • How can I assign varaibles to json response?
  • name 'df' is not defined in box plot
  • Comparing dataframe columns
  • Can I Override Global Authentication for a Single Request Type in an ApiView using DRF?
  • Celery chain performances
  • Why am I getting "asynchronous comprehension outside of an asynchronous function"?
  • Creating a file from a docker container
  • doing too many write operations in django rest framework and postgres
  • How to change the order of bar charts in Python?
  • Pandas Data Frame manipulation
  • an undefined error in a simple python code- KeyError: '284882215'
  • Pandas split column in several columns throug string replacement or regex
  • how value is passed from __init__ method in pyhton as it dose not return anyhting
  • Dynamically inherit all Python magic methods from an instance attribute
  • Asking user to input certain information
  • how to test a deep learning model in a new dataset
  • Is np.fft.fft working properly? I am getting very large frequency values
  • How can you delete similar characters at the same positions in 2 strings
  • Does insert (at the end of a list) have O(1) time complexity?
  • Automatically Creating List of Dictionaries Based Upon Two Lists of Equal Length with Python
  • Discrete Cosine Transform (DCT) Coefficient Distribution
  • multiprocessing.Pool not running on last element of iterable
  • Python: sorting string non lexicographically
  • Render images from media directory Django
  • Cannot understand why more vectorization is slower than less vectorization in this case?
  • Django - Use a property as a foreign key
  • creating a function that loops if you do not enter the correct variables
  • Confused on how to store 3D matrices in HDF5 file in matlab?
  • TOTP: Can someone use the same otp within 30s and misuse it
  • is it possible to have 2 type hints for 1 parameter in Python?
  • Can someone explain what this Numpy array property is called?
  • Better way to add the result of apply (multiple outputs) to an existing DataFrame with column names
  • Selecting choice numbers
  • Create variables from list PYTHON
  • This code takes forever to run but doesn't give an error
  • "return" and "return None" behavior difference in generator
  • AttributeError: 'str' object has no attribute 'fbind' error using kivy in Python
  • Python not importing files when not inside conda environment
  • Is it possible to override a class' __call__ method?
  • Python library for live coordinated plotting in map
  • Pandas: counting consecutive rows with condition
  • How to define that a return type of method is an implementation of superclass
  • How can I print to the Visual Studio Code console in Portuguese?
  • Google Appengine Standard Python 2.7: Can't run Google Endpoints on localhost dev_appserver.py anymore
  • google appengine Unauthorized status 401
  • Don't understand cause of this IndentationError in my tic tac toe script
  • How to read in key-value pair from a json file as a pandas dataframe?
  • Can decorator decorate a recursive function?
  • How do I create a nested for loop where I have control of the initial loop index value
  • Unexpected error when creating a SQLite database using python
  • Pythonic way to write cascading of loops and if statements?
  • Python Beginner - Having trouble with multiple choice quiz program
  • Itertools return value NOT used in combinations
  • Return a list of words that contain a letter
  • From rows to columns using Peewee ORM
  • Parse large text document, to keep only "account number", and a specific keyword ("Market Value")
  • Cannot append to my list without getting a nonetype object error
  • Python Train Test Split
  • Optimizing following Python List of Dictionary operation with better solution
  • In Pandas merge colum1 value with colum2, both col data type is object and only few values are null in first column?
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org