1.3.1定义于使用类

  • 类的定义
class class_name;
    attribute
    function
例:
class Person:
    age=18
    def say():
        print("Hello!")

1.3.2构造函数

一个特殊的方法,以两个下划线“__”开头和结尾

class Complex:
    def __init__(self, realpart,imagpart):
        self.r=realpart
        self.i=imagpart
x=Complex(3.0,2)
print(x.r,x.i)

1.3.3析构函数

另一个特殊的方法,以两个下划线“__”开头和结尾

class Complex:
    def __init__(self, realpart,imagpart):
        self.r=realpart
        self.i=imagpart
    def __del__(self):
        print("It has gone")
x=Complex(3.0,2)
print(x.r,x.i)
del x

1.3.4实例属性和类属性

属性(成员变量)有两种,一种是实例属性,一种是类属性(类变量)。
实例属性是在构造函数中定义的,定义时以self作为前缀
类属性是在类中方法之外定义的属性
在主程序中,实例属性属于(实例)对象,只能通过对象名访问,而类属性属于类,可通过类名访问,也可通过实例对象访问

例:
class Person:
    type = mammal              类属性
    def __init__(self,str,n):  构造函数
        self.name = str        实例属性
        self.sage = n
    def sat():
        ...

1.3.5私有成员和共有成员

属性名前有两个下划线“__”为为私有属性,否则为共有属性

class Car:
    price = 100
    def __init__(self, c,w):
        self.color = c          共有属性
        self.__weight = w       私有属性

car1 = Car("Red",10)
print(car1.color)
print(car1.__Car__weight)

1.3.6方法

class Fruit:
    price=100
    def __init__(self):
        self.__color = ''
    def __output(self):     私有方法
        print(self.__color) 访问私有属性
    def output(self):
        self.__output()     通过私有方法访问私有属性
    @staticmethod
    def getPrice()          定义静态方法
        return Fruit.price

1.3.7类的继承

class 派生类名(基类名)
    派生类成员

1.3.8多态

不想写了。。。

Copyright © 2024 紫云砾
Powered by .NET 8.0 on Kubernetes