开始学习Python面向对象编程

之前粗浅地学习过C++,对于面向对象有些了解,现在通过Python仔细学习一下面向对象:

类使用 class 关键字创建。类的域和方法被列在一个缩进块中。

复制代码
class Person:
  pass #pass语句表示一个空类

p = Person()
print(p)

$ python simplestclass.py
<__main__.Person object at 0x019F85F0>
#我们已经在 __main__ 模块中有了一个 Person 类的实例

复制代码

对象的方法

class Person:
    def sayHi(self):
    #定义函数的时候有self
    print('Hello, how are you?')

p = Person()
p.sayHi()
# This short example can also be written as Person().sayHi()

__init__方法

这个名称的开始和结尾都是双下划线

(感觉就像C++中的构造函数)

class Person:
    def __init__(self, name):
        self.name = name
    def sayHi(self):
      print('Hello, my name is', self.name)
    
p = Person('Swaroop')    

一个对象创立时,该函数马上运行。

类和对象变量

就像C++中的静态变量和实例变量一样,很好理解,直接看这我写的简单的一个例子:

复制代码
#Filename:claaOrInsVar
class animal:
    population = 0

    def __init__(self,name):
        self.name = name
        animal.population += 1

    def sayHi(self):
        print("My name is " + self.name)

    def howMany ( ): #这个函数没有传递参数self
  #      print('We have ' + animal.population + 'animals')
  #使用上面的代码后程序报错“    print('We have ' + animal.population + 'animals')
  #TypeError: must be str, not int”
  #animal.population 无法自动和字符串进行连接,java中是可以有表达式的自动提升的,python中却不能这样做
        print('We have {0} animals.'.format(animal.population))
an1 = animal('dogWW')
an1.sayHi()
an2 = animal('catMM')
an2.sayHi()
animal.howMany()
复制代码

继承

复制代码
class SchoolMenber:
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def tell(self):
        print('name:{0} age:{1}'.format(self.name,self.age))

class Teacher(SchoolMenber):
    def __init__(self,name,age,salary):
        SchoolMenber.__init__(self,name,age)#这里的self不要忘了写啊
        self.salary = salary

    def tell(self):
        SchoolMenber.tell(self)
        print('salary: {0}'.format(self.salary))

class Student(SchoolMenber):
    def __init__(self,name,age,mark):
        SchoolMenber.__init__(self,name,age)
        self.mark = mark

    def tell(self):
        SchoolMenber.tell(self)
        print('mark:{0}'.format(self.mark))

stu = Student('Jenny',20,95)
tec = Teacher('Mary',50,5000)
menbers = [stu,tec]
for menber in menbers:
    menber.tell()
复制代码

 

posted @   liuweistrong  阅读(200)  评论(0)    收藏  举报
编辑推荐:
· 优雅求模,一致性哈希算法
· 解疑释惑 - 日志体系之 slf4j + logback 组合(一)
· 平滑加权轮询负载均衡的底层逻辑
· C# 13 与 .NET 9 跨平台开发实战 - 第一章
· DDD领域驱动设计的理解
阅读排行:
· 《HelloGitHub》第 113 期
· Git提交错了,别慌!还有后悔药
· 开源一套Microsoft Office COM 组件的 .NET 封装
· ElasticSearch是什么?
· 优雅求模,一致性哈希算法
点击右上角即可分享
微信分享提示