python 创建对象_Python程序计算创建对象的数量

python 创建对象

We are implementing this program using the concept of classes and objects.

我们正在使用类和对象的概念来实现该程序。

Firstly, we create the Class with "Student" name with 1 class variable(counter) , 2 instance variables or object attributes (name and age), the methods are:

首先,我们使用“ Student”名称创建Class,其中包含1个类variable( counter ),2个实例变量或对象属性( name和age ),方法是:

  1. Constructor Method: This is created using __init__ inbuilt keyword. The constructor method is used to initialize the attributes of the class at the time of object creation.

    构造方法 :这是使用__init__内置关键字创建的。 构造函数方法用于在创建对象时初始化类的属性。

  2. Object Method: printDetails() is the object method, for creating object method we have to pass at least one parameter i.e. self keyword at the time of function creation. This Object method has no use in this program.

    对象方法 : printDetails()是对象方法,要创建对象方法,我们必须在函数创建时传递至少一个参数,即self关键字。 该Object方法在此程序中没有用。

For counting the number of objects created of this class, we only need one class variable and one method (which is the constructor method). In this constructor method we incrementing the class variable(counter) by one so that, Whenever an object of this class is created, constructor method is invoked automatically and incrementing the class variable by one.

计算此类创建的对象数 ,我们只需要一个类变量和一个方法(构造函数方法)。 在此构造函数方法中,我们将类变量( counter )加1,这样,无论何时创建此类的对象,构造函数方法都会被自动调用,并将类变量加1。

Below is the implementation of the program,

下面是该程序的实现,

Python代码来计数创建的对象数 (Python code to count number of objects created)

# Create a Student class
class Student :

    # initialise class variable
    counter = 0

    # Constructor method
    def __init__(self,name,age) :

        # instance variable or object attributes
        self.name = name
        self.age = age

        # incrementing the class variable by 1
        # whenever new object is created
        Student.counter += 1

    # Create a method for printing details
    def printDetails(self) :
        print(self.name,self.age,"years old")

    

# Create an object of Student class with attributes
student1 = Student('Ankit Rai',22)
student2 = Student('Aishwarya',21)
student3 = Student('Shaurya',21)

# Print the total no. of objects cretaed 
print("Total number of objects created: ",Student.counter)

Output

输出量

Total number of objects created:  3


翻译自: https://www.includehelp.com/python/program-to-count-number-of-objects-created.aspx

python 创建对象

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值