python class
时间: 2023-11-13 08:04:56 浏览: 84
A Python class is a blueprint or a template for creating objects that have similar attributes and behaviors. It defines a set of methods and properties that an object of that class will have. Classes are used for encapsulation, inheritance, and polymorphism in object-oriented programming.
A class is defined using the `class` keyword, followed by the name of the class and a colon. The body of the class is indented, and it contains the attributes and methods of the class.
Here is an example of a Python class:
```
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.")
person1 = Person("John", 30)
person2 = Person("Jane", 25)
person1.say_hello() # Output: Hello, my name is John and I am 30 years old.
person2.say_hello() # Output: Hello, my name is Jane and I am 25 years old.
```
In this example, we define a `Person` class with a constructor method `__init__` that takes two arguments, `name` and `age`. The `self` parameter refers to the instance of the class that is being created. We also define a `say_hello` method that prints out a greeting message using the instance's `name` and `age` attributes.
We create two instances of the `Person` class, `person1` and `person2`, with different names and ages. We then call the `say_hello` method on each instance to print out their greetings.
阅读全文