黑马python第二阶段第一章
类
定义和调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| class Dog: breed = "Golden Retriever" def bark(self, sound): print(f"The {self.breed} says {sound}")
my_dog = Dog()
my_dog.bark("Woof!")
|
构造方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class Dog: def __init__(self, breed, age): self.breed = breed self.age = age def display_info(self): print(f"This dog is a {self.breed} and is {self.age} years old.")
my_dog = Dog("Golden Retriever", 3)
my_dog.display_info()
|
其他类内置方法(魔术方法)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| class Dog: def __init__(self, name, age): self.name = name self.age = age
def __str__(self): return f"{self.name} is {self.age} years old"
def __lt__(self, other): return self.age < other.age
def __le__(self, other): return self.age <= other.age
def __eq__(self, other): return self.age == other.age
dog1 = Dog("Buddy", 5) dog2 = Dog("Max", 3)
print(dog1)
print(dog1 < dog2)
print(dog1 <= dog2)
print(dog1 == dog2)
|
当没有使用__eq__方法时若使用==,则对比的是内存地址。
私有成员
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| class Dog: def __init__(self, name, age): self.name = name self.__age = age
def display_info(self): print(f"{self.name} is {self.__age} years old")
def __private_method(self): print("This is a private method")
def public_method(self): self.__private_method()
my_dog = Dog("Buddy", 5)
print(my_dog.name) my_dog.display_info()
my_dog.public_method()
|
私有方法可以调用公开变量,公开方法也可以调用私有变量。在类的内部,无论是私有方法还是公开方法,都可以访问类的所有成员变量。这是因为访问权限的限制主要是针对类的外部,而不是类的内部。
继承
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class A: def method(self): return "Method from class A"
class B: def method(self): return "Method from class B"
class C(A, B):
pass
my_object = C() print(my_object.method())
|
当两个类中有相同的成员或方法名时,左边的优先级更高。
复写
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| class Animal: def __init__(self, name): self.name = name
def speak(self): return f"{self.name} makes a sound"
class Dog(Animal): def __init__(self, name, breed): super().__init__(name) self.breed = breed
def speak(self): parent_speak = super().speak() parent_speak_alt = Animal.speak(self) return f"{parent_speak} and {self.name} barks (breed: {self.breed})"
my_dog = Dog("Buddy", "Golden Retriever")
print(my_dog.speak())
|
类型注解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| name: str = "Alice" age: int = 25
height = 170
def greet(name: str) -> str: return f"Hello, {name}"
def add(a: int, b: int) -> int: return a + b
def multiply(a: int, b: int) -> int: return a * b
print(greet("Bob")) print(add(3, 5))
result = multiply(3.5, 2.5) print(result)
|
总结
- 类型注解不会影响运行时的行为。
- 静态类型检查工具:可以在开发阶段发现类型不匹配的问题,但不会影响代码运行。
- Python的动态特性:Python允许在运行时传入任何类型的参数,只要操作是合法的。
如果希望强制类型检查,可以使用静态类型检查工具(如 mypy
),或者在运行时手动检查类型(例如使用 isinstance
)。
联合类型注解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| from typing import Union
value: Union[int, str] = 42 value = "hello"
def process_value(input_value: Union[int, str]) -> Union[int, str]: if isinstance(input_value, int): return input_value * 2 elif isinstance(input_value, str): return input_value.upper()
print(process_value(10)) print(process_value("hello"))
|
多态和抽象类
1. 多态
2. 抽象类
- 包含未实现的方法(
pass
),用于定义标准,子类必须实现。
3. 作用