要利用Python命令行传递实例化对象,需要按照以下步骤进行:
1.在主程序中定义一个类,用于实例化对象。例如,定义一个Person类用于实例化人物对象。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print("Hello, my name is %s, I'm %d years old." % (self.name, self.age))
2.使用argparse模块获取命令行参数,并根据参数创建实例化对象。例如,使用argparse模块获取命令行传入的name和age参数,并根据这些参数创建Person对象。
import argparse
parser = argparse.ArgumentParser(description="Create a Person object and say hello.")
parser.add_argument('--name', type=str, help='the name of this person')
parser.add_argument('--age', type=int, help='age of this person')
args = parser.parse_args()
person = Person(args.name, args.age)
3.调用Person对象的方法。例如,调用Person对象的say_hello方法。
person.say_hello()
4.在命令行中传递相关参数,并执行程序。例如,执行下面的命令:
python main.py --name Jack --age 20
执行结果为:
Hello, my name is Jack, I'm 20 years old.
下面给出两个示例来演示这个过程。
示例1:一个计算圆形面积的程序
import argparse
import math
parser = argparse.ArgumentParser(description="Calculate the area of a circle")
parser.add_argument('--radius', type=float, help='the radius of the circle')
args = parser.parse_args()
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius * self.radius
circle = Circle(args.radius)
print("The area of the circle is:", circle.area())
在命令行中执行以下命令:
python main.py --radius 5
执行结果为:
The area of the circle is: 78.53981633974483
示例2:一个简单的人际关系管理程序
import argparse
parser = argparse.ArgumentParser(description="Manage people's relationship")
parser.add_argument('--name', type=str, help='the name of this person')
parser.add_argument('--age', type=int, help='age of this person')
parser.add_argument('--like', type=str, help='what this person likes')
args = parser.parse_args()
class Person:
def __init__(self, name, age, like):
self.name = name
self.age = age
self.like = like
def say_hello(self):
print("Hello, my name is %s, I'm %d years old. I like %s." % (self.name, self.age, self.like))
class Relationship:
def __init__(self, person1, person2):
self.person1 = person1
self.person2 = person2
def connect(self):
print("%s is connected to %s" % (self.person1.name, self.person2.name))
person1 = Person("Jack", 20, "basketball")
person2 = Person(args.name, args.age, args.like)
relationship = Relationship(person1, person2)
person1.say_hello()
person2.say_hello()
relationship.connect()
在命令行中执行以下命令:
python main.py --name Mary --age 18 --like music
执行结果为:
Hello, my name is Jack, I'm 20 years old. I like basketball.
Hello, my name is Mary, I'm 18 years old. I like music.
Jack is connected to Mary
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:利用Python命令行传递实例化对象的方法 - Python技术站