首页 > 编程知识 正文

Python 类

时间:2023-11-24 15:26:33 阅读:308608 作者:HFEO

Python 是一种完全面向对象的语言。从这些教程开始,您就一直在使用类和对象。Python 程序中的每个元素都是一个类的对象。数字、字符串、列表、词典等。,在程序中使用的是相应内置类的对象。您可以使用 type() 方法检索变量或对象的类名,如下所示。

Example: Python Built-in Classes

>>> num=20
>>> type(num)
<class 'int'>            
>>> s="Python"
>>> type(s) 
<class 'str'> 

定义类

Python 中的类可以使用class关键字来定义。

class <ClassName>:
    <statement1>
    <statement2>
    .
    .
    <statementN> 

按照上面的语法,一个类是用class关键字后跟类名和类名后面的:运算符定义的,这允许您在下一个缩进行继续定义类成员。 以下是班级成员。

  1. 职业属性
  2. 建造师T2】
  3. 实例属性
  4. 属性
  5. 课堂方法

也可以在没有任何成员的情况下定义类。以下示例使用pass关键字定义了一个空类。

Example: Define Python Class

class Student:
    pass 

类实例化使用函数表示法。要创建一个类的对象,只需调用一个类,就像一个无参数的函数,返回该类的一个新对象,如下所示。

Example: Creating an Object of a Class

std = Student() 

上图中,Student()返回Student类的一个对象,该对象被分配给一个本地变量 stdStudent类是一个空类,因为它不包含任何成员。

类别属性

类属性是直接在类中定义的变量,由类的所有对象共享。可以使用类名和对象来访问类属性。

Example: Define Python Class

class Student:
    schoolName = 'XYZ School' 

上图中schoolName是一个类内部定义的类属性。除非明确修改,否则所有对象的schoolName值将保持不变。

Example: Define Python Class

>>> Student.schoolName
'XYZ School' 
>>> std = Student()
>>> std.schoolName
'XYZ School' 

可以看到,一个类属性被Student.schoolNamestd.schoolName访问。 使用类名更改类属性的值会在所有实例中改变它。但是,使用实例更改类属性值不会反映到其他实例或类。

Example: Define Python Class

>>> Student.schoolName = 'ABC School' # change attribute value using class name
>>> std = Student()
>>> std.schoolName
'ABC School'   # value changed for all instances
>>> std.schoolName = 'My School'  # changing instance's attribute
>>> std.schoolName
'My School' 
>>> Student.schoolName # instance level change not reflectd to class attribute
'ABC School' 
>>> std2 = Student()
>>> std2.schoolName
'ABC School' 

下面的例子演示了类属性count的使用。

Example: Student.py

class Student:
    count = 0
    def __init__(self):
        Student.count += 1 

在上例中,count是 Student 类中的一个属性。 每当创建新对象时,count的值增加 1。 创建对象后,您现在可以访问count属性,如下所示。

Example:

>>> std1=Student()
>>> Student.count
1
>>> std2 = Student()
>>> Student.count
2 

构造器

在 Python 中,每当类的新对象被实例化时,都会自动调用构造器方法,与 C# 或 Java 中的构造器相同。构造器必须有一个特殊的名称__init__()和一个特殊的参数self

*Note:*The first parameter of each method in a class must be the self , which refers to the calling object. However, you can give any name to the first parameter, not necessarily self. *下面的示例定义了一个构造器。

Example: Constructor

class Student:
    def __init__(self): # constructor method
        print('Constructor invoked') 

现在,无论何时创建Student类的对象,都会调用__init__()构造器方法,如下所示。

Example: Constructor Call on Creating Object

>>>s1 = Student()
Constructor invoked
>>>s2 = Student()
Constructor invoked 

Python 中的构造器用于定义实例的属性并为其赋值。

实例属性

实例属性是附加到类实例的属性。实例属性在构造器中定义。

以下示例在构造器中定义实例属性nameage

Example: Instance Attributes

class Student:
    schoolName = 'XYZ School' # class attribute

    def __init__(self): # constructor
        self.name = '' # instance attribute
        self.age = 0 # instance attribute 

实例属性可以使用点符号[instance name].[attribute name]来访问,如下所示。

Example:

>>> std = Student()
>>> std.name
''
>>> std.age
0 

您可以使用点符号设置属性值,如下所示。

Example:

>>> std = Student()
>>> std.name = "Bill" # assign value to instance attribute
>>> std.age=25        # assign value to instance attribute
>>> std.name          # access instance attribute value
Bill
>>> std.age           # access value to instance attribute
25 

您可以通过构造器指定实例属性值。除self参数外,以下构造器还包括名称和年龄参数。

Example: Setting Attribute Values

class Student:
    def __init__(self, name, age): 
        self.name = name
        self.age = age 

现在,您可以在创建实例时指定这些值,如下所示。

Example: Passing Instance Attribute Values in Constructor

>>> std = Student('Bill',25)
>>> std.name
'Bill'
>>> std.age
25 

Note:*You don't have to specify the value of the self parameter. It will be assigned internally in Python. *您也可以为实例属性设置默认值。下面的代码设置构造器参数的默认值。因此,如果在创建对象时没有提供值,这些值将被分配给后者。

Example: Setting Default Values of Attributes

class Student:
    def __init__(self, name="Guest", age=25)
        self.name=name
        self.age=age 

现在,您可以创建一个具有默认值的对象,如下所示。

Example: Instance Attribute Default Value

>>> std = Student()
>>> std.name
'Guest'
>>> std.age
25 

更多信息请访问 Python 中的类属性与实例属性。

类别属性

在 Python 中,类中的一个属性可以使用属性()函数来定义。

Python 中的property()方法提供了实例属性的接口。 它封装实例属性并提供属性,与 Java 和 C# 相同。

property()方法以 get、set 和 delete 方法为参数,返回一个property类的对象。

以下示例演示了如何使用property()函数在 Python 中创建属性。

Example: property()

class Student:
    def __init__(self):
        self.__name=''
    def setname(self, name):
        print('setname() called')
        self.__name=name
    def getname(self):
        print('getname() called')
        return self.__name
    name=property(getname, setname) 

在上例中,property(getname, setname)返回属性对象,并将其分配给name。 因此,name属性隐藏了私有实例属性 __name。 直接访问name属性,但是在内部它将调用getname()setname()方法,如下所示。

Example: property()

>>> std = Student()
>>> std.name="Steve"
setname() called
>>> std.name
getname() called
'Steve' 

建议使用物业装饰代替property()方法。

类方法

您可以使用def关键字在一个类中定义任意多的方法。 每个方法必须有第一个参数,一般命名为self,指的是调用实例。

Example: Class Method

class Student:
    def displayInfo(self): # class method
        print('Student Information') 

Self只是类中方法的第一个参数的常规名称。 对于类的对象x,定义为mymethod(self, a, b)的方法应该称为x.mymethod(a, b)

上面的类方法可以作为普通函数调用,如下所示。

Example: Class Method

>>> std = Student()
>>> std.displayInfo()
'Student Information' 

方法的第一个参数不需要命名为self。您可以给出任何引用调用方法实例的名称。 下面的displayInfo()方法将第一个参数命名为obj而不是self,效果非常好。

Example: Class Method

class Student:
    def displayInfo(obj): # class method
        print('Student Information') 

在类中定义没有self参数的方法会在调用方法时引发异常。

Example: Class Method

class Student:
    def displayInfo(): # method without self parameter
        print('Student Information') 
>>> std = Student()
>>> std.displayInfo() Traceback (most recent call last):
std.displayInfo()
TypeError: displayInfo() takes 0 positional arguments but 1 was given 

该方法可以使用self参数访问实例属性。

Example: Class Method

class Student:
    def __init__(self, name, age): 
        self.name = name 
        self.age = age 
    def displayInfo(self): # class method
        print('Student Name: ', self.name,', Age: ', self.age) 

您现在可以调用该方法,如下所示。

Example: Calling a Method

>>> std = Student('Steve', 25)
>>> std.displayInfo()
Student Name: Steve , Age: 25 

删除属性、对象、类

您可以使用del关键字删除属性、对象或类本身,如下所示。

Example: Delete Attribute, Object, Class

>>> std = Student('Steve', 25)
>>> del std.name # deleting attribute
>>> std.name
Traceback (most recent call last):
File "<pyshell#42>", line 1, in <module>
std.name
AttributeError: 'Student' object has no attribute 'name'
>>> del std  # deleting object
>>> std.name  
Traceback (most recent call last):
File "<pyshell#42>", line 1, in <module>
std.name
NameError: name 'std' is not defined
>>> del Student  # deleting class
>>> std = Student('Steve', 25)
Traceback (most recent call last):
File "<pyshell#42>", line 1, in <module>
std = Student()
NameError: name 'Student' is not defined 

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。