Python类和对象

时间:2020-02-23 14:42:31  来源:igfitidea点击:

Python是一种面向对象的编程语言。
Python类和对象是Python编程语言的核心构建块。

Python类

到这个时候,你们所有人都应该已经了解了Python数据类型。
如果您还记得的话,python中的基本数据类型一次仅引用一种数据。

如果您可以声明一种数据类型,该数据类型本身包含多个数据类型,并且可以在任何函数的帮助下使用它们,那会怎么样? Python类为您提供了机会。

Python类是在其上创建类实例的蓝图。

简单的Python类声明

这是python类定义的基本结构。

class ClassName:  
  # list of python class variables  
  # python class constructor  
  # python class method definitions

现在,让我们来看一些真实的例子。

#definition of the class starts here  
class Person:  
  #initializing the variables  
  name = ""  
  age = 0  
    
  #defining constructor  
  def __init__(self, personName, personAge):  
      self.name = personName  
      self.age = personAge  

  #defining class methods  
  def showName(self):  
      print(self.name)  

  def showAge(self):  
      print(self.age)  
        
  #end of the class definition  

# Create an object of the class  
person1 = Person("John", 23)  
#Create another object of the same class  
person2 = Person("Anne", 102)  
#call member methods of the objects  
person1.showAge()  
person2.showName()

这个例子几乎是不言而喻的。
众所周知,以"#"开头的行是python注释。
这些注释说明了接下来的可执行步骤。
此代码产生以下输出。

Python类定义

class Person:

这行标志着" Person"类的类定义的开始。

Python类变量

#initializing the variables  
  name = ""  
  age = 0

"名称"和"年龄"是"人"类的两个成员变量。
每次我们声明此类的对象时,它将包含这两个变量作为其成员。
这部分是可选的,因为它们可以由构造函数初始化。

Python类构造函数

#defining constructor  
  def __init__(self, personName, personAge):  
      self.name = personName  
      self.age = personAge

创建类的新对象时,Python类构造函数是要执行的第一段代码。

首先,可以使用构造函数将值放入成员变量中。
您也可以在构造函数中打印消息,以确认是否已创建对象。

一旦了解python继承,我们将学习更多的构造函数角色。
构造函数方法以def __init__开头。
之后,第一个参数必须是" self",因为它传递了对类本身实例的引用。
您还可以添加其他参数,例如示例中的显示方式。
" personName"和" personAge"是要创建新对象时要发送的两个参数。

Python类方法

#defining python class methods  
  def showName(self):  
      print(self.name)

方法以以下方式声明:

def method_name(self, parameter 1, parameter 2, …….)
  statements……..
  return value (if required)

在上述示例中,我们已经看到方法showName()打印该对象的"名称"值。
前几天,我们将讨论更多有关python方法的内容。

Python类对象

# Create an object of the class  
person1 = Person("Richard", 23)  
#Create another object of the same class  
person2 = Person("Anne", 30)  

#call member methods of the objects  
person1.showAge()
person2.showName()

在python中创建对象的方式非常简单。
首先,放置新对象的名称,其后是赋值运算符,并输入带有参数的类的名称(在构造函数中定义)。

请记住,参数的数量和类型应与构造函数中接收的参数兼容。

创建对象后,可以调用成员方法并可以访问成员属性(只要它们可访问)。

#print the name of person1 by directly accessing the ‘name’ attribute
print(person1.name)