0
点赞
收藏
分享

微信扫一扫

Python面向对象学习

以下面例子作为面向对象基础介绍,类比java里的面向对象既可以,大同小异

class Employee():

raiseAmount=1.04
employeeNum=0

def __init__(self,first,surname,salary):#相当于java里面的结构体,self可以理解为this
self.first = first #属性
self.surname = surname
self.salary = salary
self.email = first + '.' + surname + '@163.com'
Employee.employeeNum+=1

def infosummary(self):#方法
return '{}, {}, {}'.format(self.first + " " + self.surname, self.salary,
self.email)
def raiseSalary(self):
self.salary = self.salary * self.raiseAmount

employee1 = Employee('Harray','Potter',4000)#声明一个实例
employee2 = Employee('peter','lee',5000)
print(employee2.infosummary())
print(employee1.infosummary())
employee2.raiseAmount=1.09#修改全局变量
employee2.raiseSalary()
print(employee2.infosummary())

子类dog,cat继承动物animal,子类继承父类所有属性,并可以重写父类方法,并可以有自己的方法。

#继承
class Animal():
name=""
def __init__(self, age, weight , height):
self.age = age
self.weight = weight
self.height = height
def eat(self):
print(self.name+' '+"is eating")

class Cat(Animal):
pass
class Dog(Animal):
def __init__(self,age,weight, height,name):
Animal.__init__(self,age,weight,height)
Animal.name=name
Animal.eat(self)
def bark(self):
print('the dog is barking')

animal=Animal(10,100,20)
animal.name='cat'
animal.eat()
cat = Cat(4,15,20)
cat.eat()#name没有初始化,所以结果的name为空
dog = Dog(5,30,50,'dog')
dog.bark()
实例方法:在类中,定义的方法,这个方法的第一个参数默认是实例对象,一般习惯使用self
类方法:在类中,定义的方法,这个方法的第一个参数默认是类对象,一般习惯用cls表示,用 @ classmethod装饰器装饰
静态方法:在类中定义的方法,这个方法的参数没有要求,用 @ staticmethod装饰器装饰
实例方法只能被实例(对象)调用
类方法和静态方法可以被类或者实例调用
class Foo(object):

# 实例方法,第一个参数必须是实例对象。一般习惯用self。
def instance_method(self):
print("是类{}的实例方法,只能被实例对象调用".format(Foo))

# 类方法, 第一个参数必须是类 对象。一般习惯使用cls。使用@classmethod装饰器装饰。

@classmethod
def class_method(cls):
print("是类方法")

# 静态方法,参数没有要求,和类没有绑定关系,就是一个普通的方法 使用@staticmethod装饰器装饰。

@staticmethod
def static_method():
print("是静态方法")


foo = Foo()

# 实例方法只能被实例调用。
foo.instance_method()

print('----------')

# 类方法可以被类或者实例调用。
Foo.class_method()
foo.class_method()

print('----------')

# 静态方法可以被类或者实例调用。
Foo.static_method()
foo.static_method()

对于Python的私有类属性不可以修改,但可以通过方法来实现对私有属性的控制。

class Animal():
name=""
def __init__(self, age, weight , height):
self.__age = age #私有的,不能被访问
#self.age = age #可以被访问
self.weight = weight
self.height = height
def eat(self):
print(self.name+' '+"is eating")
@property
def age(self):
return self.__age
def setAge(self,age):
if isinstance(age,int):
self.__age = age
@age.setter
def age(self,age):
if isinstance(age,int):#实现对属性进行修改时进行检查
self.__age = age

cat = Animal(12,23,34)
print(cat.age)
dog = Animal(22,22,22)
#print(dog.__age)#报错,无法访问私有属性
print(dog.age)
dog.setAge(29)
print(dog.age)
dog.age=37#直接赋值
print(dog.age)

作者:你的雷哥

本文版权归作者所有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。

举报

相关推荐

0 条评论