Python Class Tutorial: Create and Use Classes in Separate Files (Beginner)
Here's a simple Python class you can run in another Python file:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print('Hello, my name is', self.name, 'and I am', self.age, 'years old.')
# Create an instance of the Person class
person1 = Person('John', 30)
# Call the say_hello method on the person1 instance
person1.say_hello()
To use this class in another Python file, simply import it and create an instance:
from my_module import Person
# Create an instance of the Person class
person1 = Person('John', 30)
# Call the say_hello method on the person1 instance
person1.say_hello()
Make sure the class is saved in a separate Python file named 'my_module.py' within the same directory as your main Python file.
原文地址: https://www.cveoy.top/t/topic/lMT2 著作权归作者所有。请勿转载和采集!