-
Notifications
You must be signed in to change notification settings - Fork 2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
4.1 Python 高级编程之面向对象编程 #8
Comments
类和实例定义类class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score class后面紧接着是类名,即Student,类名通常是大写开头的单词,紧接着是(object),表示该类是从哪个类继承下来的,继承的概念我们后面再讲,通常,如果没有合适的继承类,就使用object类,这是所有类最终都会继承的类。 一些概念
|
访问限制
|
继承和多态
class Animal(object):
def run(self):
print('Animal is running...')
class Dog(Animal):
def run(self):
print('Dog is running...')
class Cat(Animal):
def run(self):
print('Cat is running...')
dog = Dog()
dog.run()
cat = Cat()
cat.run() 参考 |
静态语言 VS. 动态语言举个🌰: class Animal(object):
def run(self):
print('Animal is running...')
class Dog(Animal):
def run(self):
print('Dog is running...')
class Timer(object):
def run(self):
print('Start...')
def run_twice(animal):
animal.run() 我们在上面定义了三个类,这三个类都实现了
run_twice(Dog())
run_twice(Animal())
run_twice(Timer()) |
获取对象信息class Animal(object):
def __init__(self, name='Animal'):
self.name = name
def run(self):
print('Animal is running...')
class Dog(Animal):
pass
def func():
pass 使用
|
实例属性和类属性实例属性给实例绑定属性的方法是通过实例变量,或者通过self变量: class Student(object):
def __init__(self, name):
self.name = name
s = Student('Bob')
s.score = 90 类属性可以直接在class中定义属性,这种属性是类属性,归类所有: class Student(object):
name = 'Student' 当我们定义了一个类属性后,这个属性虽然归类所有,但类的所有实例都可以访问到。 s = Student()
print(s.name)
print(Student.name) |
|
日期:2018.07.12 周四
参考:
The text was updated successfully, but these errors were encountered: