Python进阶8---面向对象基础1
生活随笔
收集整理的這篇文章主要介紹了
Python进阶8---面向对象基础1
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
面向對象
語言的分類
Python的類
定義
class ClassName:pass class MyCalss:"""A example class"""#文檔字符串x = 'abc'#類屬性def foo(self):#類屬性foo,也是方法return 'myclass'類對象及類屬性
?
實例化
a = MyClass() #實例化__init__方法
class MyCalss:def __init__(self):#初始化print('init')a = MyCalss()實例對象
?
self
class Person:def __init__(self):print(id(self))c = Person() #會調用__init__ print('p={}'.format(id(c))) #輸出結果: 43079160 c=43079160實例變量和類變量
?
class Person:age = 7height = 175def __init__(self,name,age=23):self.name = nameself.age = agetom = Person('tom') jerry = Person('jerry',20)Person.age = 30 print(Person.age,tom.age,jerry.age) print(Person.__dict__,tom.__dict__,jerry.__dict__,sep='\n')Person.height += 5 print(Person.__dict__,tom.__dict__,jerry.__dict__,sep='\n')tom.height = 176 print(Person.__dict__,tom.__dict__,jerry.__dict__,sep='\n')Person.weight = 65 print(Person.__dict__['weight']) print(tom.__dict__['weight'])#KeyError裝飾一個類
?
#增加類變量 def add_name(name,cls):cls.NAME = name #動態增加類屬性#改進成裝飾器(帶參) def add_name1(name):def wrapper(cls):cls.NAME = namereturn clsreturn wrapper@add_name1('tom') class Person:AGE = 1print(Person.NAME)?類方法和靜態方法
普通函數
類方法
?
?
靜態方法
方法的調用
class Person:def normal_method():print('nomal')def method(self):print("{}'s method ".format(self))@classmethoddef class_method(cls):print('class = {0.__name__} {0}'.format(cls))cls.HEIGHT =175@staticmethoddef static_method():print(Person.HEIGHT)#~~~類訪問~~~ print(1,Person.normal_method()) # print(2,Person.method())#報錯 print(3,Person.class_method()) print(4,Person.static_method()) #~~~實例訪問~~~ tom = Person() # print(5,tom.normal_method())#報錯 print(6,tom.method()) print(7,tom.class_method()) print(8,tom.static_method())?
訪問控制
私有屬性Private
?
一般來說,可以在內部自定義一個方法來訪問私有變量。私有變量的本質
?
保護變量
?
?
?私有方法
?
?
私有方法的本質
?
私有成員的總結
補丁?
#test1.py from test2 import Person from test3 import get_scoredef monkeypatch4Person():Person.get_score = get_scoreprint(Person().get_score()) monkeypatch4Person()print(Person().get_score())#輸出如下: {'English': 78, 'Chinese': 86, 'History': 82} #打補丁前 {'name': 'Person', 'English': 88, 'Chinese': 90, 'History': 85} #打補丁后 #test2.py class Person:def get_score(self):ret = {'English':78,'Chinese':86,'History':82}return ret #test3.py def get_score(self):return dict(name=self.__class__.__name__,English=88,Chinese=90,History=85)屬性裝飾器
?
class Person:def __init__(self,chinese,english,history):self._chinese = chineseself._eng = englishself.__his = historydef gethis(self):return self.__hisdef sethis(self,value):self.__his = valuedef seteng(self,value):self._eng = value@propertydef chinese(self):return self._chinese@chinese.setterdef chinese(self,value):self._chinese = value@chinese.deleterdef chinese(self):# del self._chineseprint('del self._chinese')#x = property(getx, setx, delx, "I'm the 'x' property.")eng = property(lambda self:self._eng,seteng)student = Person(80,90,88) print(student.chinese)#80 student.chinese = 100 print(student.chinese)#100 del student.chinese print(student.eng)#90 student.eng =110 print(student.eng)#110對象的銷毀
方法重載(overload)
?
重寫也就是覆蓋的意思,即override。封裝
練習
?
#1.其結構值得參考! from random import randint class RandomGenerator:def __init__(self,count=10,start=1,stop=100):self.count = countself.start = startself.stop = stopself.gen = self._generatr()def _generatr(self):while True:yield [randint(self.start,self.stop) for _ in range(self.count)]def gengerate(self,count):self.count = countreturn next(self.gen)rg = RandomGenerator() lst = rg.gengerate(10) print(lst) #2 class Point:def __init__(self,x,y):self.x = xself.y = ydef __repr__(self):return '{}:{}'.format(self.x,self.y) lst1 = [Point(*v) for v in zip(rg.gengerate(10),rg.gengerate(10))] print(lst1) #輸出如下: [36:14, 84:20, 31:84, 68:82, 36:48, 87:67, 64:49, 8:15, 55:73, 90:75] #3 class Car:def __init__(self,mark=None,color=None,price=None,speed=None):self._mark = markself._color = colorself._price = priceself._speed = speedclass CarInfo:def __init__(self):self.lst = []def addcar(self,car:Car):self.lst.append(car)def showcarinfo(self):return self.lst #4 class Temperature:def __init__(self,t,unit='c'):self._c = Noneself._f = Noneself._k = Noneif unit == 'k':self._c = self.k2c(t)self._k = telif unit == 'f':self._c = self.f2c(t)self._f = telse:self._c = t@propertydef k(self):if self._k is None:self._k = self.c2k(self._c)return self._k@propertydef f(self):if self._f is None:self._f = self.c2f(self._c)return self._f@propertydef c(self):return self._c@classmethoddef c2f(cls,c):return c*9/5+32@classmethoddef f2c(cls,f):return (f-32)*5/9@classmethoddef c2k(cls,c):return c+273.15@classmethoddef k2c(cls,k):return k-273.15@classmethoddef f2k(cls,f):return cls.c2k(cls.f2c(f))@classmethoddef k2f(cls,k):return cls.c2f(cls.k2c(k))print(Temperature.c2f(40)) print(Temperature.c2k(40)) print(Temperature.f2c(104.0)) print(Temperature.f2k(104.0)) print(Temperature.k2c(313.5)) print(Temperature.k2f(313.5))t = Temperature(40) print(t.c,t.f,t.k)t = Temperature(313.5,'k') print(t.c,t.f,t.k) #簡單購物車 class Color:RED = 0BLUE = 1GREEN = 2BLACK = 3GOLDEN = 4OTHER = 100class Item:def __init__(self,**kwargs):self.__info = kwargsdef __repr__(self):return str(sorted(self.__info.items()))class Cart:def __init__(self):self.items = []def additem(self,item:Item):self.items.append(item)def gatallitems(self):return self.itemsmycart = Cart() myphone = Item(mark='Iponhe',color=Color.GOLDEN,memory='64G') mycart.additem(myphone) mycar = Item(mark='BMW',color=Color.BLACK,memory='220/s') mycart.additem(mycar) print(mycart.gatallitems())轉載于:https://www.cnblogs.com/xiaoshayu520ly/p/10715456.html
總結
以上是生活随笔為你收集整理的Python进阶8---面向对象基础1的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 成为一个小的管理者
- 下一篇: 分支结构,循环结构,for循环,九九乘法