I just started working with OOP in Python and I'm asked to create a class named Square with a specific attribute called position, which is of type tuple. So for each Square object there is a particular method to print it, given the size attribute (prints '#' of size*size) and position attribute (starts at coordenates (x, y)) but when I have an AttributeError in the init method which tells me:
AttributeError: 'Square' object has no attribute '_Square__position'
Here's the code:
class Square:
''' create Square instance with public attributes
size and position '''
def __init__(self, size=0, position=(0, 0)):
self.size = size
self.position = position
''' retrieve size and make it private'''
@property
def size(self):
return self.__size
''' set private size attribute '''
@size.setter
def size(self, value):
if type(value) is not int:
raise TypeError("size must be an integer")
if value < 0:
raise ValueError("size must be >= 0")
self.__size = value
''' retrieve position and make it private '''
@property
def position(self):
return self.__position
''' set private position attribute '''
@position.setter
def position(self, value):
if value[0] < 0 or value[1] < 0:
raise TypeError("position must be a tuple of 2 positive integers")
self.__position[0] = value[0]
self.__position[1] = value[1]
''' calculates area of square '''
def area(self):
return self.__size ** 2
''' print a square of # the size of self.__size'''
def my_print(self):
if self.__size == 0:
print()
else:
for line in range(self.__position[1]):
print()
for i in range(self.__size):
for space in range(self.__position[0]):
print(" ", end="")
for j in range(self.__size):
print('#', end="")
print()
Any help is appreciated, thanks!
CodePudding user response:
Your __init__()
method should be like this:
def __init__(self, size=0, position=(0, 0)):
self.__size = size #<-- dunder
self.__position = position #<-- dunder
Edit
Thanks to @tdelaney who pointed out that position
is a tuple which doesn't allow item assignment. So, your @position.setter
should be like this:
@position.setter
def position(self, value):
if type(value) != tuple or value[0] < 0 or value[1] < 0:
raise TypeError("position must be a tuple of 2 positive integers")
self.__position = value