Python Class Constructors and Instance Initialization

Sdílet
Vložit
  • čas přidán 18. 05. 2022
  • Class constructors are a fundamental part of object-oriented programming in Python. They allow you to create and properly initialize objects of a given class, making those objects ready to use.
    This is a portion of the complete course, which you can find here:
    realpython.com/courses/using-...
    The rest of the course covers:
    - Fine-tune object creation by overriding .__new__()
    - Subclassing immutable Built-in Types
    - Returning instances of a different class
    - Allowing only a single instance of your class (singleton)

Komentáře • 6

  • @pythonicman6074
    @pythonicman6074 Před 2 lety

    انت مبدع

  • @eles108
    @eles108 Před 2 lety +1

    Thanks

  • @serychristianrenaud
    @serychristianrenaud Před 2 lety

    Thank

  • @orangasli2943
    @orangasli2943 Před rokem

    I believe there is no initializer list-like where you just need to pass in the constant value to the constructor as parameters..
    Let say I have a class "Point" which has x,y,z to be passed in the Point to constructor..it is fine..
    But then if I make a class "Triangle"
    I want to take three "Points" with it
    When defining Triangle object I have difficulty passing in the parameters like in c++ using the initializer list with the '{' '}' and pass in the constant/literal accordingly..but there are no options like this in python..
    I need to give the name first to all the points before I can pass it to the triangle constructor..
    Is there any way I can do this?
    I tried using the *args by python but it seems it can only used for one tuple not more than that..I requested three tuples but it says it cannot do it..
    I guess I want to write code back in c++

    • @rdean150
      @rdean150 Před rokem +2

      You can indeed do this with *args.
      class Point:
      def__init__(self, x, y, z):
      self.x = x
      self.y = y
      self.z = z
      def __repr__(self):
      return f"Point({self.x}, {self.y}, {self.z})"
      class Triangle:
      def __init__(self, *points):
      if len(points) != 3:
      raise ValueError()
      self.points = points
      t = Triangle( *[Point(1, 2, 3), Point(4, 5, 6), Point(7, 8, 9)] )
      for point in t.points:
      print(point)

    • @rdean150
      @rdean150 Před rokem +2

      You can do the same with named attributes by using **kwargs instead of *args.
      But the important thing here is that this requires the __init__ to accept the arguments, which is not quite the same as initializer lists, which allow arbitrary assignment of attributes, regardless of constructor signature.
      There are succint ways if doing arbitrary names assignments in python also, but still not exactly like initializer lists.