一.类和对象:
创建类:
class 类名:
def 方法名(self,xxx)
pass
创建对象:
对象 = 类名()
对象调用方法:
对象.方法名()
二.什么时候使用面向对象?
当一些函数具有相同参数时,可以使用面向对象的方式,对参数值一次性封装到对象,以后对对象取值即可:
class SQLHelper: def fetch(self,sql): print(sql) print(self.hhost) print(self.uusername) print(self.pwd) def delte(sel,sql): pass def remove(self,sql): pass def create(self,sql): pass obj = SQLHelper() obj.hhost = "www.baidu.com" obj.uusername = "jiang" obj.pwd = "123" obj.fetch("select * from A")
三.构造方法
当构造对象时,_init_方法自动执行
class SQLHelper:
def __init__(self,a1,a2,a3): print("执行构造方法") self.hhost = a1 self.uusername = a2 self.pwd = a3def fetch(self,sql): print(sql) print(self.hhost) print(self.uusername) print(self.pwd)def delte(sel,sql): passdef remove(self,sql): passdef create(self,sql): pass obj1 = SQLHelper("www.baidu.com","jiang","123") obj1.fetch("select * from A") obj2 = SQLHelper("www.sina.com","chen","123") obj2.fetch("select * from B")
四.应用场景
eg:
class Person: def __init__(self,name,age,money): self.name = name self.age = age self.money = money def shoping(self): self.money = self.money - 2 long = Person("chen",22,600) hu = Person("jiangll",25,20000) bao = Person("love",50,230000) bao.shoping() print(bao.money) hu.shoping() print(hu.money)