class Shape:
def __init__(self, x, y, name, age):
self.x = x
self.y = y
self.name = name
self.age = age
description = "This shape has not been described yet"
author = "Nobody has claimed to make this shape yet"
def area(self):
return self.x * self.y
def perimeter(self):
return 2 * self.x + 2 * self.y
def describe(self,text):
self.description = text
def authorName(self,text):
self.author = text
def scaleSize(self,scale):
self.x = self.x * scale
self.y = self.y * scale
如何在authorName,describe和scaleSize中打印属性,因为到目前为止我只能实现这个结果。
objectname = Shape(8,10, 'Peter Adom', '55')
print(objectname.name)
print(objectname.area())
print(objectname.perimeter())
答案 0 :(得分:1)
你可以看到函数area
和perimeter
有一个return
子句,因为它们应该计算一些不能直接访问的东西(你有{{1} }和x
但您没有存储区域或周长的属性。
这在编程中很常见,因为如果您有y
属性,这可能与area
计算的值不同,从而带来不一致。
方法self.x * self.y
,describe
和authorName
用于更改对象的某些属性。它们不返回任何内容,它们在对象中设置值。
为了检索对象的属性,您应该直接访问它们。但这对scaleSize
和description
不起作用,因为您没有在对象命名空间中设置属性。事实上,方法author
中的行应该是:
__init__
之后你就能做到:
self.description = "This shape has not been described yet"
self.author = "Nobody has claimed to make this shape yet"
您应该考虑以明确其目的的方式命名您的二传手,例如objectname = Shape(8,10, 'Peter Adom', '55')
print(objectname.author) # Nobody has claimed to make this shape yet
objectname.authorName("Me")
print(objectname.author) # Me
print(objectname.description) # This shape has not been described yet
objectname.describe("Wonderful shape")
print(objectname.description) # Wonderful shape
和setAuthor
。