您的位置:首页 > 其它

面向基础操作

2019-02-27 19:16 246 查看

#======类和对象

class Student():

ID=0

name=’’

address=’’

def hs(self):

print(self.ID,self.name,self.address)

zs=Student()

zs.ID=1001

zs.name=‘张三’

zs.address=‘北京’

zs.hs()

ls=Student()

ls.ID=1002

ls.name=‘李四’

ls.address=‘南京’

ls.hs()

ww=Student()

ww.ID=1002

ww.name=‘李四’

ww.address=‘南京’

ww.hs()

class Student():

count=0

def init(self,name,age,xiaomao):

self.name=name

self.age=age

self.xiaomao=xiaomao

Student.count+=1

def say(self):

print(self.name,self.age)

zs=Student(‘张三’,18,‘小猫’)

print(zs.name,zs.age,zs.xiaomao)

zs.say()

ls=Student(‘李四’,21,‘小猫’)

print(ls.name,ls.age,ls.xiaomao)

ls.say()

print(Student.count)

class Student():

def init(self,name):

self.name=name

def say(self):

print(self.ID,self.sex)

def hehe(self):

self.ID=1001

self.sex=‘男’

zs=Student(‘张三’)

zs.hehe()

zs.say()

print(zs.name,zs.ID,zs.sex)

class Student():

def hehe(self,name):

self.name=name

def haha(self):

self.hh=12

def p(self):

self.zhu=‘zhutou’

zs=Student()

zs.hehe(‘张三’)

print(zs.name)

zs.p()

print(zs.zhu)

#===================================================为对象添加属性

class Student():

count=0#类属性

def init(self,name,age,sex):#初始化

self.name=name#增加属性对象

self.age=age

self.sex=sex

Student.count+=1

# def say(self):
#     print(self.name,self.age,self.sex)

zs=Student(‘张三’,18,‘男’)

ls=Student(‘李四’,23,‘女’)

zs.count=10

lww=Student(‘王五’,23,‘女’)

# zs.say()

# ls.say()

delattr(zs,‘count’)

print(zs.count)

print(Student.count)

print(ls.count)

#-------------------------------------

class Student():

def init(self,name):

self.name=name

zs=Student(‘张三’)

print(zs.name)

delattr(zs,‘name’)

print(zs.name)

#------------------类方法---------------------------------

class Student():

count=5

def init(self,name):#实例方法,也叫对象方法

self.name=name

@classmethod#定义 类方法

def hh(cls):#类方法第一个参数是类

print(cls.count)

def say(self):

print(self.name)

zs=Student(‘张三’)

Student.hh()

zs.say()

zs.hh()

Student.say()

#==============================================静态方法

class Student():

count=5

def init(self,name):

self.name=name

@staticmethod

def hs():

print(‘我只是一个方法,跟类和对象没有任何关系’)

zs=Student(‘张三’)

zs.hs()

Student.hs()

====================================================

class Student():
count=5
def init(self,name):
self.name=name
@staticmethod
def hs():
print(‘我只是一个方法,跟类和对象没有任何关系’)
@classmethod
def hh(cls,cls1,cls2):
print(cls.countcls1cls2)
@staticmethod
def hs(cls1,cls2):
print(cls1cls2)
def cc(self,n):
print(self.namen)
zs=Student(‘张三’)
Student.hh(3,4)
Student.hs(3,4)
zs.cc(2)
#3种方法:类方法,对象方法,静态方法;
#类方法和实例方法区别如下:

1、在类方法中不能调用实例方法,只能访问和自己一样的类方法,但实例方法可以访问类方法和实例方法。

2、在类方法中不能引用实例变量(用static修饰的变量),但实例方法可以引用成员变量和实例变量。

3、在类方法中不能使用super、this关键字。

4、类方法不能被覆盖,但实例方法可以被覆盖。

5、类方法的调用是:类名.类方法,而实例方法的调用必须new出一个对象,即:对象.实例方法。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: