OOP总结
- 参考:https://realpython.com/python3-object-oriented-programming/#what-is-object-oriented-programming-oop
what’s OOP
- Definition: is a programming paradigm which provides a means of structuring programs so that properties and behaviors are bundled into individual objects.
- 类似于一个人有名字、年龄、地址等属性
Classes in python
- Definition: classes are used to create user-defined data structures that contain arbitrary information about something.
Python Objects(instances)
- 实例
How to define a class in Python
Instance Attributes
- self是用来记录每一个类的实例
class Dog:
# Class Attribute
species = 'mammal'
# Initializer / Instance Attributes
def __init__(self, name, age):
self.name = name
self.age = age
作业:Using the same Dog class, instantiate three new dogs, each with a different age. Then write a function called, get_biggest_number(), that takes any number of ages (*args) and returns the oldest one. Then output the age of the oldest dog like so:
The oldest dog is 7 years old.
class Dog:
# Class Attribute
species = 'mammal'
# Initializer / Instance Attributes
def __init__(self, name, age):
self.name = name
self.age = age
# Instantiate the Dog object
jake = Dog("Jake", 7)
doug = Dog("Doug", 4)
william = Dog("William", 5)
# Determine the oldest dog
def get_biggest_number(*args):
return max(args)
Instance Methods
- 用来获取实例内容
class Dog:
# Class Attribute
species = 'mammal'
# Initializer / Instance Attributes
def __init__(self, name, age):
self.name = name
self.age = age
# instance method
def description(self):
return "{} is {} years old".format(self.name, self.age)
# instance method
def speak(self, sound):
return "{} says {}".format(self.name, sound)
# Instantiate the Dog object
mikey = Dog("Mikey", 6)
# call our instance methods
print(mikey.description())
print(mikey.speak("Gruff Gruff"))
调整属性
>>> class Email:
... def __init__(self):
... self.is_sent = False
... def send_email(self):
... self.is_sent = True
...
>>> my_email = Email()
>>> my_email.is_sent
False
>>> my_email.send_email()
>>> my_email.is_sent
True
Python Object Inheritance
# Parent class
class Dog:
# Class attribute
species = 'mammal'
# Initializer / Instance attributes
def __init__(self, name, age):
self.name = name
self.age = age
# instance method
def description(self):
return "{} is {} years old".format(self.name, self.age)
# instance method
def speak(self, sound):
return "{} says {}".format(self.name, sound)
# Child class (inherits from Dog class)
class RussellTerrier(Dog):
def run(self, speed):
return "{} runs {}".format(self.name, speed)
# Child class (inherits from Dog class)
class Bulldog(Dog): # 继承
def run(self, speed):
return "{} runs {}".format(self.name, speed)
# Child classes inherit attributes and
# behaviors from the parent class
jim = Bulldog("Jim", 12)
print(jim.description())
# Child classes have specific attributes
# and behaviors as well
print(jim.run("slowly"))