首頁  >  文章  >  後端開發  >  Python類別的基本使用方法有哪些

Python類別的基本使用方法有哪些

WBOY
WBOY轉載
2023-05-17 23:58:045281瀏覽

1、物件導向

類別(class):是用來描述具有相同屬性和方法的物件的集合。

類別變數:類別變數在整個實例化的物件中是公用的。一般定義在類別中且在函數體之外。

方法:類別中的函數

資料成員:類別變數或實例變數用於處理類別及其實例物件的相關的資料。

方法重寫:如果從父類別繼承的方法不能滿足子類別的需求,可以對其進行改寫,這個過程叫方法的覆寫(override),也稱為方法的重寫。

局部變數:定義在方法中的變量,只作用於目前實例的類別。

實例變數:在類別的宣告中,屬性是用變數來表示的,這種變數稱為實例變量,實例變數就是用 self 修飾的變數。

繼承:即一個衍生類別(derived class)繼承基底類別(base class)的欄位和方法。繼承也允許把一個衍生類別的物件當作一個基底類別物件。就像我們定義一個fruit(水果)類,然後又定義了一個fruit類的衍生類apple(蘋果),它有著fruit類的一些屬性和方法,也有著自己的一些獨特的屬性和方法,和fruit類是一種'is-a'的關係。

實例化:類別的一個具體對象,類別像當於一個模板,只有我們將其實例化為一個對象後才能對其進行相應的操作。

物件:透過類別定義的資料結構實例。物件包括兩個資料成員(類別變數和實例變數)和方法。


2、類別定義

定義一個類別:

class ClassName:....    ....    ....

類別名稱建議採用駝峰式命名,或是全部大寫字母


3、使用類別物件方法

類別物件支援兩種運算:屬性參考與實例化

屬性參考:和python中的其他語法一樣,obj.name

在類別中帶__的屬性為類別的私有屬性,私有屬性在類別外部無法直接存取,像__name.

class Fruit:#这是类的一个基本属性self.number = 100def get_number(self):                a = self.number + 100return a

f = Fruit()print('We have {0} fruits'.format(f.number))print('We have {0} fruits'.format(f.get_number()))

輸出結果:

We have 100 fruitsWe have 200 fruits

4、建構方法

python類別中有一個名為__init__()的特殊方法,叫做建構方法,該方法在類別中進行實例化時會自動進行呼叫(可以用於類別屬性初始化等),類似C 裡面類別的建構子。

def __init__(self):self.data = []

類別定義了 __init__() 方法,類別的實例化操作會自動呼叫__init__()方法。

class Fruit:def __init__(self):                print('你已经实例化了一个对象')
f = Fruit()

輸出結果

你已经实例化了一个对象

init_() 方法可以有參數,參數透過 init() 傳遞到類別的實例化操作。

class Complex:def __init__(self,real,image):self.r = realself.i = imagedef get_complex(self):                print('complex real is %.2f , image is %.2f'%(self.r,self.i))
a = Complex(3.5,-3)a.get_complex()

輸出結果如下:

complex real is 3.50 , image is -3.00

self代表類別的實例,而非類別。類別的方法與普通的函數只有一個特別的區別-它們必須有一個額外的第一個參數名稱, 按照慣例它的名稱是 self。但self並不是Python中的關鍵字哦。

不知是否可以這樣理解,self就代表的是你依照一個類別實例化一個物件後的物件的位址。很像C 類別中this指標

class Test:def prt(self):        print(self)        print(self.__class__)
t = Test()t.prt()

輸出:

<__main__.Test object at 0x0000025EC6D45608><class &#39;__main__.Test&#39;>

#5、類別的方法

在類別的內部,使用def關鍵字來定義一個方法,與一般函數定義不同,類別方法必須包含參數self, 且為第一個參數。如果不需要self傳遞參數,需要在函數前面加上@staticmethod,表示靜態方法

class Complex:def __init__(self, real=None, image=None):self.r = realself.i = image
def get_complex(self):        print('complex real is %.2f , image is %.2f' % (self.r, self.i))
    @staticmethoddef test(a, b):        print('complex real is %.2f , image is %.2f' % (a, b))

a = Complex(3.5, -3)a.get_complex()
b = Complex()b.test(3, -2)

輸出結果

complex real is 3.50 , image is -3.00complex real is 3.00 , image is -3.00

6、繼承

Python 同樣支援類別的繼承,格式如下:

class Derivedclassname(Baseclassname):    ...    ...

Baseclassname(基底類別名稱)必須與衍生類別定義在一個作用域內。除了類,還可以用表達式,基類定義在另一個模組中時這一點非常有用:

class Fruit:    def __init__(self,sweet):        self.sweetness = sweet    def describe(self):        print('Our fruit has a sweetness of %.2f'%self.sweetness)
class Apple(Fruit):#单继承,继承fruit类    def __init__(self,sweet,color):        self.color = color        Fruit.__init__(self,sweet)    def describe(self):#改写基类fruit的方法        print('Our apple has a sweetness of {0:.2f}%,and color is {1}'.format(self.sweetness,self.color))

apple = Apple(62.2,'red')apple.describe()

##輸出:

Our apple has a sweetness of 62.20%,and color is red

多繼承

Python同樣可以繼承多個基底類別:

class Derivedclassname(basename1,basename2,...):    ...    ...    ...

需要注意圓括號中父類別的順序,若是父類別中有相同的方法名,而在子類別使用時未指定,python從左至右搜索,即方法在子類別中找不到時,從左到右查找父類別中是否包含方法。

class Fruit:def __init__(self, sweet):        self.sweetness = sweetdef describe(self):        print('Our fruit has a sweetness of %.2f' % self.sweetness)

class Food:def __init__(self, uprice, num):        self.unit_price = uprice        self.number = num        self.total_price = num * upricedef cost(self):        print('You need to pay {0:.3} yuan, thank you'.format(self.total_price))

class Apple(Fruit, Food):def __init__(self, sweet, color, uprice, num):        self.color = color        Fruit.__init__(self, sweet)        Food.__init__(self, uprice, num)def describe(self):        print('Our fruit has a sweetness of {0:.2f}%,and color is {1}'.format(self.sweetness, self.color))
apple = Apple(62.2,'red',3.5,21)apple.describe()apple.cost()

輸出:

Our fruit has a sweetness of 62.20%,and color is redYou need to pay 73.5 yuan, thank you

7、方法重写

如果父类方法的功能不能满足你的需求,你可以在子类重写你父类的方法,如果想调用已经被覆盖的基类方法,可以用super(子类名,子类实例对象名).父类方法

class Parent_class:def Method(self):         print ('父类方法')

class Child_class(Parent_class): # 定义子类def Method(self):        print ('子类方法')

c = Child_class()                # 子类实例化c.Method()                  # 子类调用重写方法super(Child_class,c).Method()    #用子类对象调用父类已被覆盖的方法

子类继承父类构造函数

如果在子类中需要父类的构造方法就需要显式地调用父类的构造方法,或者不重写父类的构造方法。

class A:def __init__(self, x, y):        self.x = x        self.y = y        print('pos is ({0},{1})'.format(self.x, self.y))
def xxx(self):        print('parent now')

class B(A):def xxx(self):        print('child now')

b = B(10, 3)b.xxx()

输出

pos is (10,3)child now

如果重写了__init__ 时,实例化子类,就不会调用父类已经定义的 __init__。

如果重写了__init__ 时,要继承父类的构造方法,可以使用 super 关键字super(子类,self).__init__(参数1,参数2,....),或者父类名称.__init__(self,参数1,参数2,...)


8、类的私有属性

两个下划线开头,声明该属性为私有,像__name不能在类的外部被使用或直接访问。在类内部的方法中使用时 self.__name。

class JustCounter:     __secretCount = 0  # 私有变量    publicCount = 0  # 公开变量
def count(self):        self.__secretCount += 1        self.publicCount += 1       print(self.__secretCount)

counter = JustCounter()counter.count()counter.count()print(counter.publicCount)print(counter.__secretCount)  # 报错,实例不能访问私有变量
Traceback (most recent call last):File "test.py", line 16, in <module>    print (counter.__secretCount)  # 报错,实例不能访问私有变量AttributeError: 'JustCounter' object has no attribute '__secretCount'

两个下划线开头,声明该方法为私有方法,像__private_method,只能在类的内部调用 ,不能在类的外部调用。self.___private_method。

class Site:def __init__(self, name, url):        self.name = name  # public        self.__url = url  # private
def who(self):        print('name  : ', self.name)        print('url : ', self.__url)
def __foo(self):  # 私有方法        print('这是私有方法')
def foo(self):  # 公共方法        print('这是公共方法')        self.__foo()

x = Site('***', 'www.xxx.com')x.who() # 正常输出x.foo() # 正常输出x.__foo()  # 报错

输出:

'''name  :  ***url :  www.***.com这是公共方法这是私有方法Traceback (most recent call last):  File "F:\Python\Program\test.py", line 61, in <module>    x.__foo()      # 报错AttributeError: 'Site' object has no attribute '__foo''''

类的专有方法

__init__ : 构造函数,在生成对象时调用,类似C++构造函数

__del__: 析构函数,释放对象时使用,类似C++析构函数,常用在释放申请的内存空间

__repr__: 打印,转换。这个个函数就是在打印类的时候,控制类输出的字符串

class Name:def __init__(self, name):        self.name = name

print(Name('s'))
'''<__main__.Name object at 0x0000023744AFD248>'''
class Name:def __init__(self,name):        self.name = name
def __repr__(self): #控制了在打印类时候的输出          return 'Name({!r})'.format(self.name)

print(Name('s'))
'''Name('s')'''

__setitem__ : 每当属性被赋值的时候都会调用该方法,因此不能再该方法内赋值 self.name = value 会死循环

__getitem__: 当访问不存在的属性时会调用该方法

__len__: 获得长度,如果一个类表现得像一个list,要获取有多少个元素,就得用len() 函数。要让len()函数工作正常,类必须提供一个特殊方法__len__(),它返回元素的个数。

class CountList:def __init__(self, *args):        self.list = [x for x in args]        self.count = self.__len__()
def __len__(self):         return len(self.list)
def get_count(self):         return self.count

a = CountList(1, 2, 3, 4, 4, 5)print(a.get_count())print(len(a))

__cmp__: 比较运算

__call__: 函数调用

__add__: 加运算

__sub__: 减运算

class MyClass:
def __init__(self, height, weight):        self.height = height        self.weight = weight
# 两个对象的长相加,宽不变.返回一个新的类def __add__(self, others):        return MyClass(self.height + others.height, self.weight + others.weight)
# 两个对象的宽相减,长不变.返回一个新的类def __sub__(self, others):        return MyClass(self.height - others.height, self.weight - others.weight)
# 说一下自己的参数def intro(self):        print("高为", self.height, " 重为", self.weight)

def main():    a = MyClass(height=10, weight=5)    a.intro()
    b = MyClass(height=20, weight=10)    b.intro()
    c = b - a    c.intro()
    d = a + b    d.intro()

if __name__ == '__main__':    main()
'''高为 10  重为 5高为 20  重为 10高为 10  重为 5高为 30  重为 15'''

__mul__: 乘运算

__truediv__: 除运算

__mod__: 求余运算

__pow__: 乘方

同样的。类的专有方法也可以重写

以上是Python類別的基本使用方法有哪些的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除