write python class coding, run the class in other python file, give 2 file names, simple for beginner
Here is an example of a simple Python class that creates a "Person" object:
person.py:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
And here's an example of how you can use this class in another Python file:
main.py:
from person import Person
# Create two person objects
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)
# Call the say_hello() method on each person object
person1.say_hello()
person2.say_hello()
When you run the main.py file, you should see the following output:
Hello, my name is Alice and I am 25 years old.
Hello, my name is Bob and I am 30 years old.
Note that in this example, person.py and main.py are in the same directory. If they were in different directories, you would need to adjust the import statement accordingly.
原文地址: https://www.cveoy.top/t/topic/yZl 著作权归作者所有。请勿转载和采集!