python - class

class

  • An object made by a class template is called an instance of that class.
  • A class is a template for making an instance, and the instance reflects the structure provided by the template, the class.
  • It is important to remember that the class defines the structure and operations of an instance but that those operations are operations for class instances, not the class itself.


summary

Classes

  • Classes are objects.
  • Object-oriented programming (OOP) has three concepts: encapsulation, inheritance,
    polymorphism.
  • Creating a new class creates a new type.
  • A class is to its instance as a cookie cutter is to a cookie.
  • Classes have attributes and methods that act on those attributes. r Attributes are usually created within the init method.
  • The identifier self refers to the current instance.
  • The first parameter of methods is self.
  • Class structure
class ClassName(object):
      def init (self,param1=4):
            self.att = param1 # create attribute. 
      def str (self):
            return "some string" # return a string for printing 
      def some method(self,param):
            # do something
  • Overloading operators:
    A + B maps to A.add (B) which maps to add (self,param) by mapping A to self and mapping B to param.
  • Inheritance: inherit properties of the superclass

simple student class

class Student(object):
    def __init__(self, first='', last='', id=0):  # initializer
        self.first_name_str = first
        self.last_name_str = last
        self.id_int = id

    def __str__(self):  # string representation, for printing
        return "{} {}, ID:{}".format \
            (self.first_name_str, self.last_name_str, self.id_int)
stu1 = Student('terry', 'jones', 333)
print(stu1)

object-oriented programming (OOP)

Object-oriented programming is a powerful development tool. It is particularly supportive of the divide-and-conquer style of problem solving. If you can organize your design thoughts around OOP, you can design large programs around basic objects.
The concept of self is important in understanding how class objects work, especially in the creation and use of instances. Reread this chapter if you feel that you have not yet grasped the concept of self in Python classes.

import math


class Point(object):
    def __init__(self, x_param=0.0, y_param=0.0):
        self.x = x_param
        self.y = y_param

    def distance(self, param_pt):
        x_diff = self.x + param_pt.x
        y_diff = self.y + param_pt.y
        return math.sqrt(x_diff ** 2 + y_diff ** 2)

    def sum(self, param_pt):
        newpt = Point()
        newpt.x = self.x + param_pt.x
        newpt.y = self.y + param_pt.y
        return newpt

    def __str__(self):
        print("called the __str__ method")
        return "({:.2f},{:.2f})".format(self.x, self.y)
class NewClass(object):
    def __init__(self, attribute='default', name='Instance'):
        self.name = name  # public attribute
        self.__attribute = attribute  # 'private' attribute

    def __str__(self):
        return '{} has attribute {}'.format(self.name, self.__attribute)

More on classes

classes, types, introspection

mapping operators to special methods

class MyClass(object):
    def __init__(self, param1 = 0):
        print('in constructor')
        self.value = param1 # set a local instant variable named value 

    def __str__(self):
        print('in str')
        return 'Val is : {}'.format(str(self.value))

    def __add__(self, param2):
        print('in add')
        result = self.value + param2.value
        return MyClass(result)

Inheritance

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末狼钮,一起剝皮案震驚了整個濱河市碳柱,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌熬芜,老刑警劉巖莲镣,帶你破解...
    沈念sama閱讀 216,372評論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異涎拉,居然都是意外死亡瑞侮,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,368評論 3 392
  • 文/潘曉璐 我一進店門鼓拧,熙熙樓的掌柜王于貴愁眉苦臉地迎上來半火,“玉大人,你說我怎么就攤上這事毁枯〈鹊蓿” “怎么了?”我有些...
    開封第一講書人閱讀 162,415評論 0 353
  • 文/不壞的土叔 我叫張陵种玛,是天一觀的道長藐鹤。 經(jīng)常有香客問我,道長赂韵,這世上最難降的妖魔是什么娱节? 我笑而不...
    開封第一講書人閱讀 58,157評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮祭示,結(jié)果婚禮上肄满,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好稠歉,可當我...
    茶點故事閱讀 67,171評論 6 388
  • 文/花漫 我一把揭開白布掰担。 她就那樣靜靜地躺著,像睡著了一般怒炸。 火紅的嫁衣襯著肌膚如雪带饱。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,125評論 1 297
  • 那天阅羹,我揣著相機與錄音勺疼,去河邊找鬼。 笑死捏鱼,一個胖子當著我的面吹牛执庐,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播导梆,決...
    沈念sama閱讀 40,028評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼轨淌,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了看尼?” 一聲冷哼從身側(cè)響起猿诸,我...
    開封第一講書人閱讀 38,887評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎狡忙,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體址芯,經(jīng)...
    沈念sama閱讀 45,310評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡灾茁,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,533評論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了谷炸。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片北专。...
    茶點故事閱讀 39,690評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖旬陡,靈堂內(nèi)的尸體忽然破棺而出拓颓,到底是詐尸還是另有隱情,我是刑警寧澤描孟,帶...
    沈念sama閱讀 35,411評論 5 343
  • 正文 年R本政府宣布驶睦,位于F島的核電站,受9級特大地震影響匿醒,放射性物質(zhì)發(fā)生泄漏场航。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,004評論 3 325
  • 文/蒙蒙 一廉羔、第九天 我趴在偏房一處隱蔽的房頂上張望溉痢。 院中可真熱鬧,春花似錦、人聲如沸孩饼。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽镀娶。三九已至立膛,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間汽畴,已是汗流浹背旧巾。 一陣腳步聲響...
    開封第一講書人閱讀 32,812評論 1 268
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留忍些,地道東北人鲁猩。 一個月前我還...
    沈念sama閱讀 47,693評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像罢坝,于是被迫代替她去往敵國和親廓握。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,577評論 2 353

推薦閱讀更多精彩內(nèi)容