Программа сохраняет изображения как объекты. Он хранит размер, цвет рамки и описание изображения. Программа должна ввести свои требования к изображению. Пользователь вводит цвет, ширину и высоту. Затем программа выполнит поиск в массиве и выведет описание изображения, если какое-либо изображение соответствует требованиям.
class Picture:
def __init__(self, DescriptionP, WidthP, HeightP, FrameColourP):
self.__Description = DescriptionP # string
self.__Width = WidthP # integer
self.__Height = HeightP # integer
self.__FrameColour = FrameColourP # string
def getDescription(self):
return self.__Description # Fixed method to return the associated attribute to the user
def getWidth(self):
return self.__Width
# Key rule: Only use parameters if they are passed, otherwise only use self and attributes.
def getHeight(self):
return self.__Height
def getFrameColour(self):
return self.__FrameColour
# In such questions, do not think much just solve normally. Use the parameters(mentionned...
def SetDescription(self, DescriptionP):
# ...during class definition) and imagine that they have already been given a value by the user.
self.__Description = DescriptionP
# Do this to show blank array instead of doing the method where you write 'None' multiple times.
PictureArray = []
# This is class with parameters so can happen directly but can't be blank. In case of...
for i in range(100):
# ...object with parameters, it has to be defined first(tho can be blank there at least).
PictureArray.append(Picture("", 0, 0, ""))
def ReadData(PictureArray): # In object case array is not needed as parameter.
filename = "C:\\Users\\ayush\\Downloads\\Pictures.txt"
NumberPicturesInArray = 0
try:
file = open(filename, "r")
# For internal work so .lower() used in string case, or bcoz extra variable avoided.
Description = (file.readline()).strip().lower()
while (Description != ""):
# Just prefer mentionning data type for int(and .lower() here for string).
Width = int((file.readline()).strip())
Height = int((file.readline()).strip())
Frame = ((file.readline()).strip()).lower()
# Extra step to do when without 'object'...
PictureArray[NumberPicturesInArray] = Picture(
Description, Width, Height, Frame)
# ...where '.append' can be thought to be replaced with '[Counter]='.
Description = ((file.readline()).strip()).lower()
NumberPicturesInArray = NumberPicturesInArray+1
PictureArray.append(Picture(DescriptionP=Description,
WidthP=Width, HeightP=Height, FrameColourP=Frame))
file.close()
except IOError:
print("Could not find file!")
return NumberPicturesInArray, PictureArray
# In the without 'object' case, when a return value is...
# ...there in function then use it to call the function.
NumberPicturesInArray, PictureArray = ReadData(PictureArray)
# .lower allows any case alphabets to be input but be processesed as lower only!
FrameColour = input("Input the Frame colour ").lower()
MaxWidth = int(input("Input the Maximum Width "))
MaxHeight = int(input("Input the Maximum Height "))
print("Matches Frames shown")
for Z in range(0, NumberPicturesInArray): # This range is crucial.
if (PictureArray[Z].getFrameColour() == FrameColour):
if (PictureArray[Z].getWidth() <= MaxWidth):
if (PictureArray[Z].getHeight() <= MaxHeight):
print(PictureArray[Z].getDescription(), " ", str(PictureArray[Z].getWidth()), " ", str(
PictureArray[Z].getHeight()), " ", PictureArray[Z].getFrameColour())
Я получаю сообщение об ошибке
if (PictureArray[Z].getFrameColour() == FrameColour):
AttributeError: 'Picture' object has no attribute 'getFrameColour'
Я пытаюсь вызвать метод для чтения данных массива.
Ожидаемый результат - Описание изображения
Если ваш код действительно выглядит так, то он не может работать. В Python отступ является частью синтаксиса, указывающего, когда блок заканчивается. Проверьте отступ в своем фактическом, я подозреваю, что он отключен, учитывая сообщение об ошибке, которое вы нам показываете.
@CrazyChucky тщательно редактирует код, где проблема, вероятно, связана с неправильным отступом. Если вы угадали неправильно, вы в конечном итоге получите ошибочные ответы.
@AndrasDeak--СлаваУкраїні В целом верно, но в данном случае я не менял никаких отступов, только границы кода.






Ваш метод __init__ имеет правильный отступ внутри класса Picture. Однако другие «методы» вообще не имеют отступа, поэтому на самом деле они не являются частью класса; это просто функции верхнего уровня. Поэтому, когда вы создаете экземпляр Picture, у него нет метода getFrameColour.
Вы хотите что-то еще вроде этого:
class Picture:
def __init__(self, DescriptionP, WidthP, HeightP, FrameColourP):
self.__Description = DescriptionP #string
self.__Width = WidthP #integer
self.__Height = HeightP #integer
self.__FrameColour = FrameColourP #string
def getDescription(self):
return self.__Description
def getWidth(self):
return self.__Width
def getHeight(self):
return self.__Height
def getFrameColour(self):
return self.__FrameColour
Это все еще имеет некоторые проблемы. Стандартной практикой в Python является использование «snake_case», например, использование get_frame_colour вместо getFrameColour; что еще более важно, вам вообще не нужны методы получения. Было бы намного чище использовать атрибуты напрямую. Вы также можете попробовать классы данных, чтобы упростить работу.
Пожалуйста, отредактируйте форматирование вашего кода, пока код здесь не будет выглядеть точно так же, как ваш реальный код. Точное вдавливание спасает жизни.