1、类与对象
类与对象是面向对象编程的两个主要方面。一个类(Class) 能够创建一种新的类型(Type) ,其中对象(Object) 就是类的实例(Instance) 。可以这样来类比:你可以拥有类型 int 的变量,也就是说存储整数的变量是 int 类的实例(对象)。
2、self
self相当于JAVA中的this,表示对自身对象的引用。在定义方法的时候,self是必带的,使用方法的时候,self会自动赋值。
class myClass1:
def myFun1(self, arg1):
print("arg1 is:", arg1)
myclass1 = myClass1()
myclass1.myFun1(666)
3、__ init __
__ init __ 方法会在类的对象被实例化(Instantiated) 时立即运行。这个方法的作用是在对象初始化的时候做一些操作,并且实现带参数创建对象。
class myClass2:
def __init__(self,name):
self.name = name
def printSayHi(self):
print("Hi,", self.name)
myclass2 = myClass2("Tom")
myclass2.printSayHi()
4、类变量/对象变量
类变量(Class Variable) 是共享的(Shared) ——它们可以被属于该类的所有实例访问。该类变量只拥有一个副本,当任何一个对象对类变量作出改变时,发生的变动将在其它所有实例中都会得到体现。
对象变量(Object variable) 由类的每一个独立的对象或实例所拥有。在这种情况下,每个对象都拥有属于它自己的字段的副本,也就是说,它们不会被共享,也不会以任何方式与其它不同实例中的相同名称的字段产生关联。
输入:
class Dog:
count = 0 #类变量
def __init__(self, name):
self.name = name #对象变量
def getUp(self):
print(self.name," get up!")
self.__class__.count += 1
print("there are ",self.__class__.count," dogs")
def gotoBed(self):
print(self.name," go to bed!")
self.__class__.count -= 1
print("there are ",self.__class__.count," dogs")
@classmethod #表征此函数属于类
def showDogs(cls):
print("oh my god, there are ",cls.count," dogs!")
dog1 = Dog("Jack")
dog2 = Dog("Tom")
dog1.getUp()
dog2.getUp()
Dog.showDogs()
dog1.gotoBed()
dog2.gotoBed()
Dog.showDogs()
输出:
Jack get up!
there are 1 dogs
Tom get up!
there are 2 dogs
oh my god, there are 2 dogs!
Jack go to bed!
there are 1 dogs
Tom go to bed!
there are 0 dogs
oh my god, there are 0 dogs!
5、classmethod、staticmethod、property
在类的函数这一块,有三个比较重要的属性,具体使用方法如下:
输入:
class Parent:
hobby = 3
apple = 3
def __init__(self, age):
self.age = age
@property #代表这个函数可以当属性使用,必须有return
def Age(self):
return self.age;
@staticmethod #此方法属于静态方法
def getHobby():
print ("I have {} hobby".format(Parent.hobby))
@staticmethod #此方法属于静态方法,指责格方法调用的是此对象所属的类
def getHobby2(self):
print ("I have {} hobby".format(self.__class__.hobby))
@classmethod
def getApple(cls): #此方法属于类,cls代表这个类
print ("I have {} apples".format(cls.apple))
class Son(Parent):
hobby = 2
apple = 2
def __init__(self, age):
Parent.__init__(self,age)
self.age = age
son = Son(20)
print(son.Age)
Parent.getHobby()
Parent.getApple()
print("----")
Son.getHobby()
Son.getHobby2(son)
Son.getApple()
输出:
20
I have 3 hobby
I have 3 apples
----
I have 3 hobby
I have 2 hobby
I have 2 apples
6、继承
在面向对象中,父类或者超类是一个更抽象的概念,拥有子类中共有的特征。
输入:
class Member:
def __init__(self,name,age):
self.name = name
self.age = age
def showDetail(self):
print("my name is {},and I am {}".format(self.name,self.age))
class Teacher(Member):
def __init__(self,name,age):
Member.__init__(self,name,age)#如果子类还有其他属性,可以给self.xxx赋值
class Student(Member):
def __init__(self,name,age):
Member.__init__(self,name,age)
teacher = Teacher("Li lei", 30)
student = Student("Han Meimei", 10)
teacher.showDetail()
student.showDetail()
输出:
my name is Li lei,and I am 30
my name is Han Meimei,and I am 10