Class (CLASS): Defines the behavior that a large class of objects have.
When we create objects based on this class, each object has this common behavior.
实例化
: Create an object from a class
1. Create a class
Use the keyword class to create a
class The first letter of the class name is capitalized, with or without parentheses
The class we define should contain two parts: attributes + functions
Let's build a simple class计算器的类Calculator
class Calculator:
# 固有属性项
name = 'Good Calculator'
price = 44
# 初始化类的属性
def __init__(self,name,price,H,width=10,weight=5):
self.n = name
self.p = price
self.h = H
self.wi = width
self.we = weight
# 定义内部函数,实现相应功能
def add(self,x,y):
print(self.name) # 使用self调用属性name
result=x+y
print(result)
def minus(self,x,y):
result=x-y
print(result)
def time(self,x,y):
result=x*y
print(result)
def divide(self,x,y):
result=x/y
print(result)
2. Use class
Instantiating classes in python does not need to use the keyword new
The instantiation of classes is similar to [function calls]
# 定义实例使用该类
x = Calculator('FF',20,30)
# 'FF'代表 name
# 20 代表 price
# 30 代表 H
# 打印实例的属性进行查看 【实例名字.属性】
Here are the assigned attributes in the instance
print('默认名称:',x.name)
print('默认的价格属性:',x.price)
# 注意,这里x.name和x.n不一样【x.name是初始;x.n传入了变量】
print('实例中赋予的价格属性:',x.p)
print('实例中高度值:',x.h)
print('实例中的宽度:',x.wi)
print('实例中的重量:',x.we)
print('实例中名称:',x.n)
call a method in the class
add_ = x.add(3,4)
minus_ = x.minus(3,4)
times_ = x.time(3,4)
divide_ = x.divide(3,4)
learning link