OOP总结
what's OOPClasses in pythonPython Objects(instances)How to define a class in PythonInstance AttributesInstance Methods调整属性
Python Object Inheritance
参考: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:
species
= 'mammal'
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:
species
= 'mammal'
def __init__(self
, name
, age
):
self
.name
= name
self
.age
= age
jake
= Dog
("Jake", 7)
doug
= Dog
("Doug", 4)
william
= Dog
("William", 5)
def get_biggest_number(*args
):
return max(args
)
Instance Methods
用来获取实例内容
class Dog:
species
= 'mammal'
def __init__(self
, name
, age
):
self
.name
= name
self
.age
= age
def description(self
):
return "{} is {} years old".format(self
.name
, self
.age
)
def speak(self
, sound
):
return "{} says {}".format(self
.name
, sound
)
mikey
= Dog
("Mikey", 6)
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
class Dog:
species
= 'mammal'
def __init__(self
, name
, age
):
self
.name
= name
self
.age
= age
def description(self
):
return "{} is {} years old".format(self
.name
, self
.age
)
def speak(self
, sound
):
return "{} says {}".format(self
.name
, sound
)
class RussellTerrier(Dog
):
def run(self
, speed
):
return "{} runs {}".format(self
.name
, speed
)
class Bulldog(Dog
):
def run(self
, speed
):
return "{} runs {}".format(self
.name
, speed
)
jim
= Bulldog
("Jim", 12)
print(jim
.description
())
print(jim
.run
("slowly"))