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 ),方法是:
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__内置关键字创建的。 构造函数方法用于在创建对象时初始化类的属性。
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 创建对象