创建Dog类
class Dog:
def __init__(self,name,age):
self.name =name
self.age =age
def sit(self):
print(f"{self.name} is now sitting")
def roll_over(self):
print(f"{self.name} is now over")
my_dog =Dog('Jarvis',6)
print(my_dog.name)
print(my_dog.age)
__init__(self, , , )首位必须包含下划线,在Python中自动调用,类似于C++中的构造函数,且一定包含self这个形参,self相当于本类对象,它可以调用任何属性和方法(也叫函数)
修改属性的值一定要注意__init__()是两个下划线
与C++相同的是我们可以修改类对象的值来修改它的属性值
或者我们也可以通过方法来修改属性的值
很简单,就是新增加一个函数来对这个属性来进行修改
class Car:
def __init__(self,make,model,year):
self.make =make
self.model =model
self.year=year
self.odometer=0
def describe_car():
name =f"{self.year}{self.make}{self.model}
print( {name.title()})
print(self.odometer)
def update_odometer(mileage):
self.odometer =mileage
my_car =Car('audi','a4','2020')
my_car.update_odometer(100)
my_car.descirbe_car()
class User:
def __init__(self, login_attempts):
self.login_attempts = login_attempts
def increment_login_attempts(self, ):
self.login_attempts += 1
def rest_login_attempts(self):
self.login_attempts = 0
def describe_login_attempts(self):
print(self.login_attempts)
my_user = User(100)
my_user.increment_login_attempts()
my_user.describe_login_attempts()
my_user.rest_login_attempts()
my_user.describe_login_attempts()



