Tools, FAQ, Tutorials:
Create New Instances of a Class
How to Create a New Instance of a Class?
✍: FYIcenter.com
There are two ways to create a new instance (object) of a class (or type):
1. The short way: Call the class name as the class constructor function with the following syntax. It will return an instance of the given class.
>>> x = class_name(parameter_list)
2. The long way: Call the class "__new__()" method to get an un-initialized instance, and call the instance "__init__()" method to initialize it, with the following syntax:
>>> x = class_name.__new__(class_name) >>> x.__init__(parameter_list)
The Python code below shows you how to create instances of "user" class in 2 different ways:
>>> class user():
... nextID = 1
... def __init__(self,name="Joe",age=25):
... self.id = user.nextID
... self.name = name
... self.age = age
... user.nextID = user.nextID + 1
... def dump(self):
... print("ID: "+str(self.id))
... print("Name: "+self.name)
... print("Age: "+str(self.age))
...
>>> jeo = user("Joe",30)
>>> jeo.dump()
ID: 1
Name: Joe
Age: 30
>>>
>>> jay = user.__new__(user)
>>> jay.__init__("Jay",18)
>>> jay.dump()
ID: 2
Name: Jay
Age: 18
⇐ Where Are Class Properties Stored
2018-01-27, ∼3100🔥, 0💬
Popular Posts:
Where to find tutorials on Using Azure API Management Publisher Dashboard? Here is a list of tutoria...
What are "*..." and "**..." Wildcard Parameters in Function Definitions? If you want to define a fun...
Where to find tutorials on Using Azure API Management Developer Portal? Here is a list of tutorials ...
What is EPUB 3.0 Metadata "dc:publisher" and "dc:rights" elements? EPUB 3.0 Metadata "dc:publisher" ...
How to use 'choose ... when ..." policy statements to control execution flows? If you want to contro...