模块课程(1/4)
类和实例
类是用于创建具有数据(属性)的对象的蓝图 和行为(方法)。 实例是从创建的具体对象 班级。
最少的语法
class Cane:
def __init__(self, nome, eta):
self.nome = nome
self.eta = eta
def abbaia(self):
return f"{self.nome} dice WOOF!"
# creazione di istanze
fido = Cane("Fido", 3)
luna = Cane("Luna", 5)
fido.nome # 'Fido'
fido.abbaia() # 'Fido dice WOOF!'__init__:“构造函数”
当您创建一个对象时,__init__ 方法会被自动调用。
实例(Cane("Fido", 3))。它用于初始化属性。
从技术上讲,它不是构造函数(该对象已经由
__new__),但它是您设置初始状态的地方。
self:第一个参数
self 是对调用该方法的实例的引用。它是一个
约定(不是关键字)并且始终是实例的第一个参数
方法。
fido.abbaia()
# equivalente a Cane.abbaia(fido)
# Python passa fido come self automaticamente实例属性与类属性
class Cane:
specie = "Canis familiaris" # attributo di CLASSE (condiviso)
def __init__(self, nome):
self.nome = nome # attributo di ISTANZA (per ognuno)
fido = Cane("Fido")
luna = Cane("Luna")
fido.nome # 'Fido' (istanza)
luna.nome # 'Luna' (istanza)
fido.specie # 'Canis familiaris' (cercato sulla classe)
Cane.specie # 'Canis familiaris'多种方法和状态
class Contatore:
def __init__(self, inizio=0):
self.valore = inizio
def incrementa(self, di=1):
self.valore += di
def reset(self):
self.valore = 0
c = Contatore()
c.incrementa()
c.incrementa(di=5)
c.valore # 6
c.reset()
c.valore # 0轮到你了
使用 __init__(self, x, y) 定义一个类 `Point` 来存储属性。添加一个方法 `distance_from_origin` 返回 x^2 + y^2 的平方根。创建 `p = Point(3, 4)` 并计算 `p.distance_from_origin()`。
显示提示
math.sqrt(self.x ** 2 + self.y ** 2)
3 次尝试后可用的解决方案
复习练习
使用 __init__(self,balance=0) 定义“BankAccount”以及修改 self.balance 的“deposit(amount)”、“withdraw(amount)”方法。创建 `a = BankAccount(100)`,存入 50,取出 30。评估 `a.balance`。
显示提示
self.balance += 存款金额。
3 次尝试后可用的解决方案
额外的挑战
Define a class `Rectangle` with a constructor `__init__(self, width, height)` to set width and height, and a method `area(self)` that returns the product of width and height. Instantiate a rectangle with width `4` and height `5` storing it in `rect`, and evaluate `rect.area()`.
显示提示
请记住使用 self 来访问区域内的属性(self)。
3 次尝试后可用的解决方案