程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python Basics_ Classes and objects (I)

編輯:Python

# Classes and objects
# I understand. , But it's a little hard to use
# Concepts of classes and objects
# class : Of the same kind of transaction   Abstract description
# object : Conforming to class description   Concrete existence

# Functional encapsulation   function -
# Why should we encapsulate it into a function class ?   --- whole : Properties and functions ( Behavior )

# First of all Defining classes / Implementation class
# Generating objects
'''
class Class name ( Hump ):
    attribute
    Method ( function ( function ))
self : It's the object itself
Example method : The first parameter is self

# If you want to create objects at the same time , Customize the properties of the object
# initialization : Magical function  __init__
# When you create objects for colleagues , Automatically call .
# Class is optional
'''
# The first instance that is not initialized
# Defining classes
class Dog:     # Class name
    # kind = None
    # kind = ' String '     # Class properties   In this way, class attributes are written to death , No matter how many objects , The attributes are all this
    kind = ' Dog '    # Class properties All objects are the same

    # It's called - Method
    def bark(self):   # self It's the object itself   Class methods use functions
        print(' Wang Wang Wang Wang ....')

    # eat - Method
    def eat(self):  # Class methods use functions
        print(' Dog food ...')

    # run - Method
    def run(self):  # Class methods use functions
        print(' Run ')

    # sleep - Method
    def sleep(self):  # Class methods use functions
        print('self In itself :',self)   # Object is self
        print(' To go to sleep! ')

# Create objects that match the class --- Instantiation
# Object name = Class name ()   You can create multiple objects
cqg = Dog()    # cqg An object is Dog Class
print(' Object itself :',cqg)     # Object is self
# Through object . attribute / Method ()   To get the properties of the missing object , To invoke behavior

cqg.run()       # Calling class methods , Instantiation , But no parameters are given
cqg.eat()       # Calling class methods , Instantiation
cqg.bark()      # Calling class methods , Instantiation
cqg.sleep()     # Calling class methods , Instantiation
print(cqg.kind)     #   The print out is a class attribute

print('**************************************************')
you_jm = Dog()    # The second object created   It's another object
you_jm.eat()
you_jm.run()
you_jm.bark()
you_jm.sleep()
print(you_jm.kind)     #   The print out is a class attribute
 


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved