Python🐍

python - class

2021-01-27  本文已影响0人  Pingouin

class

summary

Classes

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

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

上一篇 下一篇

猜你喜欢

热点阅读