Python classes and errors

Working on some homework for a while now and can't seem to figure out how to get around this error. Just to note, I am not allowed to import anything.

The error I am getting I think is due to either my __repr__ or __str__ methods. Here is my code:

class Point: def __init__(self, x = 0, y = 0): """ The constructor allows the user to set values for x and y. Default values are 0. """ self.x = x self.y = y def translate(self, s, t): """ This method translates point x by s and point y by t. """ self.x = self.x + s self.y = self.y + t return self.x, self.y def __str__(self): """ This method returns a string representation of the point. """ return "({0}, {1})".format(self.x, self.y) def __repr__(self): """ This method returns a string representation of the point. """ return "({0}, {1})".format(self.x, self.y) class SimplePoly: def __init__(self, *vertices): """ The constuctor adds all vertices to a list. """ self.vertices = vertices self.pointlist = [self.vertices] def translate(self, s, t): """ This method translates all points of the polygon by (s,t). """ for p in self.pointlist: p.x + s p.y + t print(self.pointlist)

but when I try to do translate to every Point object in the self.pointlist, I get the error:

Traceback (most recent call last): File "<pyshell#170>", line 1, in <module> h.translate(1,1) File "C:/Python34/", line 74, in translate p.x + s AttributeError: 'tuple' object has no attribute 'x'

The vertices are Point objects. This is the code I am testing with:

>>> g = Point(2,3) >>> g2 = Point(5,2) >>> g3 = Point(6,7) >>> h = SimplePoly(g,g2,g3) >>> h.translate(1,1)

-------------Problems Reply------------

Your self.pointlist attribute is a list with one tuple in it:

def __init__(self, *vertices):
# ....
self.vertices = vertices
self.pointlist = [self.vertices]

vertices is always a tuple here, which in turn contains your Point() objects. Tuples never have x and y attributes; it is itself not a Point instance.

You may as well replace self.pointlist with self.vertices here. If you needed a mutable sequence, use list() instead of a list literal:

self.pointlist = list(self.vertices)

which creates a list with the elements from the tuple.

Category:python Views:1 Time:2018-04-15

Related post

  • Compound assignment to Python class and instance variables 2010-03-11

    I've been trying to understand Python's handling of class and instance variables. In particular, I found this answer quite helpful. Basically it says that if you declare a class variable, and then you do an assignment to [instance].property, you will

  • How to bind exception class and error code of external com exception? 2011-06-25

    my .NET application calls method of object that located out of assembly boundaries. When this method has thrown exception i've catched COMException. Exception contains special code in ErrorCode field, for example -123. try { // call outside object }

  • Python Classes and Iteration 2012-03-12

    I'm using the standard Python mailbox module to read messages from a Maildir. Once read, I parse them and store the results in a dict. I've put this functionality into a class and use __getitems__ to enable other components of my program to access th

  • Python classes and unittest 2012-03-27

    I'm working through python for rookies, and i've come across a question in which I had to make a class, and subclasses which is fine(i presume ive done it right) but I now have to include some testing with python unittest module and i can't figure ou

  • Python - Classes and OOP Basics 2012-04-04

    I do not fully understand classes. I have read the python documentation and several other tutorials. I get the basic gist of it but don't understand the nuance. For instance in my code here: I would like to return the clas

  • Python class argument error 2017-04-26

    I am creating a menu but i have come across an error an would like some help as i don't know what is wrong or how to fix it, the piece of code says i am putting an argument in but i have not entered an argument. class menu(object): def print_menu():

  • kohana 3 - image class and error "Cannot instantiate abstract class Image" 2010-07-22

    i made model which sends through controller to template neccessary data from database and doing picture resize for each picture path in the database. don't know why but there is some error (subj). here is code of this class method of model http://fpa

  • My first C++ class ( and error ) 2010-09-03

    I tried a naive class taken from a book I found in the office. This is it: #include <iostream.h> #include <math.h> const double ANG_RAD = 0.017; class Angulo { double valor; public: void act_valor( double ); double seno( void ); double co

  • Memory never released when using Python classes and numpy 2011-05-11

    Basically I am not going to post all of the code here but I will provide a generic example. I have a class that has a function to run and create a large array of values. This array shouldn't be much bigger than 10MB from my estimates. Within the func

  • python classes and variable scope 2011-05-13

    class Test: def c(self, args): print args def b(self, args): args.append('d') def a(self): args = ['a', 'b', 'c'] self.b(args) self.c(args) Test().a() Why doesn't this print ['a', 'b', 'c']? --------------Solutions------------- When you pass a list t

  • Python classes and __init__ method 2011-07-26

    I am learning python via dive into python. Got few questions and unable to understand, even through the documentation. 1) BaseClass 2) InheritClass What exactly happens when we assign a InheritClass instance to a variable, when the InheritClass doesn

  • How would I improve this simple python class and its docstring ? 2012-04-08

    This is a simple filter that I have been using for a project reading data over a serial connection, and thought it would be good to use it as my first attempt to write docstrings. Does anyone have any suggestions? I have been reading PEP 257. As it i

  • Python Classes and Collections 2012-04-07

    This is a best practices question Let say, I have a class object, like so: class ClassOfObjects: def __init__(self, name): = name ... Lets say, I instantiate 3 of these objects a = ClassOfObjects('one') b = ClassOfObjects('two') c = ClassOf

  • Using classes in a python program and incrementing points 2018-03-12

    I need to create a final project for a Beginning Python class and I decided to create a riddle program and want to simplify the following code, but am unsure how to do it. I would like to use a class to do this, but I'm having trouble figuring out ho

  • Adding variably named fields to Python classes 2010-05-05

    I have a python class, and I need to add an arbitrary number of arbitrarily long lists to it. The names of the lists I need to add are also arbitrary. For example, in PHP, I would do this: class MyClass { } $c = new MyClass(); $n = "hello" $c.$n = ar

  • instantiate python class from class available as string , only in memory! 2010-08-28

    I'm using Reportlab to create PDFs. I'm creating two PDFs which I want to merge after I created them. Reportlab provides a way to save a pycanvas (source) (which is basically my pdf file in memory) as a python file, and calling the method doIt(filena

  • Can I use my own Python class with numpy or some other matrix library? 2011-04-07

    I'd like to be able to do matrix operations using a Python class as the elements—in this case, a simple Galois field implementation. It implements the necessary __add__, __mul__, __sub__ etc. At first, I thought this should be possible with numpy arr

  • Pickle python class instance plus definition 2011-07-17

    This is a problem which I suspect is common, but I haven't found a solution for it. What I want is quite simple, and seemingly technically feasible: I have a simple python class, and I want to store it on disc, instance and definition, in a single fi

  • How to set python class attribute to value of another, previously defined class attribute in class definition? 2013-04-02

    I am defining a python class and would like to declare a set of class attributes, then use those attributes in initializing a list that will also be stored as a class attribute. class SampleClass( models.Model ): #------------------------------------

  • Structuring a program. Classes and functions in Python 2009-10-13

    I'm writing a program that uses genetic techniques to evolve equations. I want to be able to submit the function 'mainfunc' to the Parallel Python 'submit' function. The function 'mainfunc' calls two or three methods defined in the Utility class. The

  • Python new-style classes and __subclasses__ function 2010-05-20

    Can somebody explain to me why this works (in Python 2.5) : class Foo(object): pass class Bar(Foo): pass print(Foo.__subclasses__()) but this doesn't : class Foo(): pass class Bar(Foo): pass print(Foo.__subclasses__()) The latter returns "AttributeEr

  • python: closures and classes 2010-12-28

    I need to register an atexit function for use with a class (see Foo below for an example) that, unfortunately, I have no direct way of cleaning up via a method call: other code, that I don't have control over, calls Foo.start() and Foo.end() but some

  • Django Modelform giving isinstance() arg 2 must be a class, type, or tuple of classes and types error 2011-04-25

    Getting the following error on a specific view: isinstance() arg 2 must be a class, type, or tuple of classes and types Request Method: GET Request URL: ***********CHANGED FOR PRIVACY Django Version: 1.3 Exception Type: TypeError Exception Value: isi

  • no Error Messages in imported python classes 2011-07-14

    i have a couple of python classes, which i import and use in my main program. ## path to classes sys.path.append(basePath + "classes") ## import some classes import mainmod mainModHandler = mainmod.Mainmod() I have no problem, working with them, but

  • python class HTMLParser incorrectly giving parse error 2011-12-24

    Consider the following html input: <html> <head> <script> function open_tools(tool_div) { document.getElementById("tool1").innerHTML = "<a href='javascript:void(0);' onclick=\"javascript:clos_tools('""');\"><img src='menu.g

Copyright (C), All Rights Reserved.

processed in 0.131 (s). 11 q(s)