Skip to content

Latest commit

 

History

History
220 lines (159 loc) · 7.81 KB

Class.md

File metadata and controls

220 lines (159 loc) · 7.81 KB

← back to Main Page


Classes

Basics on Classes

Objects and Classes

  • Objects
    Data(Variables, Attributes) or Codes(Functions, Methods)
    Objects are THE UNIQUE INSTANCE of something concrete.

  • Classes
    Number 7, String 'keyboard' and Function adder are Objects, Each of them represents something concrete. Number 7 represents An Attribute 'Number' Seven, Using Class int.
    String keyboard represents An Attribute 'Word' keyboard, Using Class str.
    and Function adder represents A Function 'Code' _adder', Using Class function.

  • Methods
    Classes have Methods. Methods are Functions defined within Classes. For example, str Class has .find() or .upper() Methods.
    These Methods are defined in str Class and called for some operation with its Attribute(Data) keyboard.
    ( Class Methods, Static Methods)

In Object-Oriented Programming(OOP), Attributes & Methods are hierarchically classificated into Classes.
Classes are sort of boxes, which is classificated by its usage.
(A steel box for heavy things, a paper box for books, and a plastic box for fishes or water thing.)
Like this, Each Classes are defined & ready to deal with Data & Codes.
With Instance, Classes are instantiated and Objects that have some concrete things are generated.


Defining Classes

  • class Statements
    You can make Classes with class Statements.
class Membership:
    pass

It's an empty Class. Like Functions, We can assign this Class and generate an Object.

someone = Membership()
someone
<__main__.Person object at 0x7fac781345f8> # An Object with __main__ Module, Person Class
  • __init__ Methods : Object Initialization

Let's make another one.

class Membership:
    def __init__(self, name):
        self.name = name
    def introduce(self):
        print("Hello, I'm a member,", self.name)

bruce = Membership('Bruce Lee')    # Instance bruce
bruce.introduce()                  # Hello, I'm a member, Bruce Lee

__init__ Methods is called when A Class is instantiated! __init__ Methods initialize a UNIQUE Class from Classes Definition when Objects are generated.

self is the First Arguments refer to the Instance itself. It is invisible when bruce Instance is generated(We delivered only one argument in Membership('Bruce Lee')), but automatically delivered to Python Method.

__init___ Method should have one Argument, which refer to the Instance itself. It should be the first Argument of __init___ Method. The word 'Self' is generally used and highly recommended for its name.


Class Variables and Method Variables

Let's define a basic Class.

class Membership:
    count = 0
    def __init__(self, name):
        self.fullname = name
        Membership.count += 1
    def introduce(self):
        print("Hello, I'm a member,", self.fullname)
    def __del__(self):
        Membership.count -= 1

bruce = Membership('Bruce Lee')    # Instance bruce
bruce.introduce()                  # Hello, I'm a member, Bruce Lee
bruce.fullname                     # Bruce Lee
bruce.count                        # 1

paul = Membership('Paul Phoenix')  # Instance paul
paul.introduce()                   # Hello, I'm a member, Paul Phoenix
paul.fullname                      # Paul Phoenix
paul.count                         # 2

In Person() Classes, some Objects are defined.

Object Description
count A Class Variable
__init__ A Method
self An Argument refer to each Instance itself.
name A Local Variable within init Method
fullname A Instance Variable(self.fullname)

Class Variable is shared by all Instance.
Instance Variable should be unique to each Instance, not interrupting each other.

paul.fullname is a Instance Variable, so It has an Unique name. paul.count is A Class Variable, so It has an Shared number, 2.


Scopes and Namespaces

As the previous case , you saw two kinds of Variables have different Value-sharing ranges. This ranges are named Namespaces, literally. It's the mapping between Names and Objects, so Namespaces are mostly made of Dictionaries.

To show the Namespaces, use __dict__ Methods, which is the Built-in Methods.

bruce.__dict__ # {'name': 'Bruce Lee'}
paul.__dict__  # {'name': 'Paul Phoenix'}
Membership__dict__
# mappingproxy({'__weakref__': <attribute '__weakref__' of 'Membership' objects>, '__del__': <function Membership.__del__ at 0x7fe9da53f400>, 'count': 2, '__init__': <function Membership.__init__ at 0x7fe9da53f2f0>, '__dict__': <attribute '__dict__' of 'Membership' objects>, '__module__': '__main__', 'introduce': <function Membership.introduce at 0x7fe9da53f378>, '__doc__': None})

You can see name Variables are in the Instance Namespaces and count Variable is in the Class Namespace. When you call .count Variable from each Instances, Python searches it from Instances first, and then from Classes next. That's how paul.count returns 2.

Scopes: global > nonlocal > local

  • global Statements
    As the above, Objects in Functions or Methods are not shared. It means that Methods normally returns only Objects with return Statements. By using global Statements, we can get more Objects existing within Methods.

  • nonlocal Statements
    By Using nonlocal Statements, we can access variables existing over local Scopes. as the following, nonlocal Statements can access deposit& withdraw Functions to balance Variable, which is non-global.

def bank_account1(initial_balance) :
    balance = initial_balance
    def deposit(amount) :
        balance += amount     # Error
        return balance
    def withdraw(amount) :
        balance -= amount
        return balance
    return deposit, withdraw
 
d, w = bank_account1(100)
print(d(100))


def bank_account1(initial_balance) :
    balance = initial_balance
    def deposit(amount) :
        nonlocal balance
        balance += amount
        return balance
    def withdraw(amount) :
        nonlocal balance
        balance -= amount
        return balance
    return deposit, withdraw
 
d, w = bank_account1(100)
print(d(100))
200
def scope_test():
    def do_local():
        spam = "local spam"

    def do_nonlocal():
        nonlocal spam
        spam = "nonlocal spam"

    def do_global():
        global spam
        spam = "global spam"

    spam = "test spam"
    do_local()
    print("After local assignment:", spam)
    do_nonlocal()
    print("After nonlocal assignment:", spam)
    do_global()
    print("After global assignment:", spam)

scope_test()
print("In global scope:", spam)

# After local assignment: test spam
# After nonlocal assignment: nonlocal spam
# After global assignment: nonlocal spam
# In global scope: global spam

↑ Up to the Top

Add new Methods

Just use def Statements to define new Functions!


← back to Main Page