#学习笔记Python#10、对象(14)&11、对象(14下)&12、对象(14尾)

版权声明:作者:cheese0_0,转载请注明出处来自https://blog.csdn.net/cheese0_0 商业转载请联系作者获得授权,非商业转载请注明出处 https://blog.csdn.net/cheese0_0/article/details/82805286

10、对象(14)
2017-08-16 17:10
对象要有属性和方法。
属性就是对象的一些信息,描述。

ball.color                     ball.size                     ball.weight

可以显示 print (ball.color)
可以赋值 ball.color=‘green’
可以把他们赋值给常规的、不是对象的变量 myColor=ball.color
还可以把他们赋给其他对象的属性:myball.color =yourball.color
方法就是可以对对象做的操作,它们是一些代码块,可以调动这些代码块来完成某个工作,就是包含在对象中的函数。
函数能做到的,方法都能做到,包括传递参数和返回值。

ball.kick()             ball.threw()

对象=属性+方法
利用对象,就是把一个东西的属性和方法(你知道和你可以做的事情)收集在一起,属性就是信息,方法就是动作。

点记法

创建对象
S1:定义对象看上去什么样,会做什么,也就是它的属性和方法。但是创建这个描述并不会真正创建一个对象,这只是一个蓝图。
S2:第二就是使用类来建立一个真正的对象。这个对象称为这个类的一个实例。
例:创建一个简单的ball类

class ball:       #这里告诉Python我们在建立一个类
    def bounce(self):
          if self.direction=="down":
              self.direction="up"

是一个球的类定义,其中只有一个方法bounce()
属性并不属于类。属性属于各个实例。因为每个实例可以有不同的属性。

    class ball:  #这里告诉Python我们在建立一个类
          def bounce(self):
              if self.direction=="down":
                  self.direction="up"

#建立类的一个实例,设置一些属性

    myball=ball()
    myball.direction='down'
    myball.color='red'
    myball.size='small'

#打印对象的属性
print("I just created a ball.")
print("my ball is",myball.size,myball.color)
print(myball.direction)

#使用一个方法
myball.bounce()
print("now the ball's direction is",myball.direction)

结果:
I just created a ball.
my ball is small red
down
now the ball's direction is up

初始化对象:在创建对象时设置属性
初始化:把它设置为我们希望设置的状态或条件,以备使用。

增加一个__init__函数

    class ball:
          def __init__(self,color,size,direction):
              self.color=color
              self.size=size
              self.direction=direction
  # 这里是__init__()方法。init前后各有两条下划线,总共四条    
      def bounce(self):
          if self.direction=="down":
              self.direction="up"
              
myball=ball("red","small","down")
print("I just created a ball.")        #属性作为__init__()的参数传入

print("my ball is",myball.size,myball.color)
print(myball.direction)

myball.bounce()
print("now the ball's direction is",myball.direction)

结果与上面一样,不同的是这里用了__init__()方法来设置属性,会在对象创建时完成初始化。每个对象都内置一个__init__()方法。如果你在内定义中没有加入自己的__init__()方法,就会有这样一个内置方法接管,他的工作就是创建对象。

—————————————————————————————————————
11、对象(14下)
2017-08-17 23:14
Python中,在你创建类时Python会自动包含一些方法。Python工作员通常把他们叫做特殊方法 。
我们已经知道,init()方法会在对象创建时完成初始化。每个对象都内置一个__init__()方法。如果你在类定义中没有加入自己的__init__()方法,就会有一个内置方法接管,它的工作就是创建对象。
另一种特殊方法是__str__()改变打印对象的方式。
(⊙o⊙)…补一下,Python中有一个约定是类名总以大写字母开头

class ball:
      def __init__(self,color,size,direction):
          self.color=color
          self.size=size
          self.direction=direction
          
      def __str__(self):
          msg="hi,i'm a "+ self.size +" "+ self.color +" ball!"
          return msg
              
myball=ball("red","small","down")
print(myball)

结果:hi,i’m a small red ball!

如果不加__str__(),直接print myball,是不会得到结果的

什么是self?使用一个类可以创建多个对象实例

cartersball=ball(“red”,“small”,“down”)
warrensball=ball(“green”,“medium”,“up”)

调用其中一个实例的方法时,像这样:warrensball.bounce().
方法必须知道是哪个实力调用了他,self参数会告诉方法哪个对象调用它。这称为实例引用。
在调用方法时,warrensball.bounce()的括号里没有参数,但是方法里却有一个self参数。
调用一个类方法时,信息会自动传递给方法。这就像写成:ball.bounce(warrensball)
self这个名字在Python中没有任何特殊的含义,只不过所有人都使用这个实例引用名,这是让代码更易读懂的一个约定。

msg=msg.strip(",")删除字符串首尾字符(,空)
一个示例:
Hotdog

class HotDog:
      def __init__(self):
          self.cooked_level=0
          self.cooked_string="Raw"
          self.condiments=[]
          
      def __str__(self):
          msg="hot dog"
          if len(self.condiments)>0:
              msg=msg+"with"
          for i in self.condiments:
              msg=msg+i+","
          msg=msg.strip(",")
          msg=self.cooked_string+" "+msg+"."
          return msg
      
      def cook(self,time):
          self.cooked_level=self.cooked_level + time
          if self.cooked_level>8:
              self.cooked_string="Charcoal"
          elif self.cooked_level>5:
              self.cooked_string="Well-done"
          elif self.cooked_level>3:
              self.cooked_string="Medium"
          else:
              self.cooked_string="Raw"
      def addCondiment(self,condiment):
          self.condiments.append(condiment)
          
        
myDog= HotDog()
print (myDog)
print("cooking hot dog for 4 minutes...")
myDog.cook(4)
print (myDog)
print("cooking hot dog for 3 more minutes...")
myDog.cook(3)
print (myDog)
print("What happens if i cook it for 10 more minutes")
myDog.cook(10)
print (myDog)
print("Now,i'm going to add some stuff on my hot dog" )
myDog.addCondiment("ketchup")
myDog.addCondiment("mustard")
print (myDog)

结果:

Raw hot dog.
cooking hot dog for 4 minutes...
Medium hot dog.
cooking hot dog for 3 more minutes...
Well-done hot dog.
What happens if i cook it for 10 more minutes
Charcoal hot dog.
Now,i'm going to add some stuff on my hot dog
Charcoal hot dogwithketchup,mustard.

—————————————————————————————————————
12、对象(14尾)
2017-08-19 22:50

隐藏数据
查看和修改属性有两种方法:

mydog.cooked_level=5        
   mydog.cook(5)

多态——同一个方法,不同的行为
多态是对于不同的类,可以有同名的两个(或多个)方法。取决于这些方法分别应用到哪个类,它们可以有不同的行为。
例:

class Triangle:
    def __init__(self,width,height):
        self.width=width
        self.height=height
    def getArea(self):
        area=self.width*self.height/2.0
        return area
class Square:

        def __init__(self,size):
            self.size=size
        def getArea(self):
            area=self.size*self.size
            return area
        
    mytriangle=Triangle(4,5)
    mysquare=Square(7)
    A=mytriangle.getArea()
    B=mysquare.getArea()
    print(A)
    print(B)

结果:

10.0
49

继承:

class Gameobject:
    def __init__(self,name):
        self.name=name
    def pickup(self,player):
        pass                关键字,作为一个占字符
        #put code here to addathe object
        #to the player's collection

代码桩:程序员编写比较复杂的代码时通常就会采用这种注释的方式来组织想法,“空”函数或方法称为代码桩。

class Coin(Gameobject):       #coin是gameobject的子类
    def __init__(self,value):
        Gameobject.__init__(self,'coin')      #继承gameobject的初始化方法,并补充新内容
    self.value=value
def spend(self,buyer,seller):
    pass
    #put code here to remove the coin       #coin类新的spend方法
    #from the buyer's money and
    #add it to the seller's money

猜你喜欢

转载自blog.csdn.net/cheese0_0/article/details/82805286