How to create an object in python without using __init__ - python

So for this piece of code
class CircleT:
def __init__(self,x,y,r):
self.x = x
self.y = y
self.r = r
Lets say I want to create a CircleT object named Circle1.
I would just have to do
Circle1 = CircleT(2,4,6)
But if I had this instead
class CircleT:
def CircleT(self,x,y,r):
self.x = x
self.y = y
self.r = r
How would I go about creating the Circle1 object?

Related

Python & Pylance: Self-referential code warnings - is there a way to type hint a function argument with the class that it's in?

Looking for a touch of help. This is really a Pylance (in VSCode on a Mac) troubleshooting question...
I have a class that is essentially an XY coordinate and I would like to have a function that receives another instance of the class itself to check for proximity:
class coOrd:
def __init__(self, x, y, minProx):
self.x = x
self.y = y
self.minProx = minProx
def checkProx(self, coOrdToChk)->bool:
proximity = math.sqrt((self.x - coOrdToChk.x)**2 + (self.x - coOrdToChk.x)**2)
if proximity < self.minProx or proximity < coOrdToChk.minProx:
return False
return True
The code works, Pylance just has a persistent warning, but is there a way to use type hinting without getting errors from Pylance? It would make the remaining coding way easier with the typing suggestions and typo checking.
I tried this and it also works, but is very clunky. Basically declaring the class with the properties that you want to access in a sibling-referencing-function, then overwrite the whole thing again...
# Bulky pre-declaration
class coOrd:
def __init__(self, x, y, minProx):
self.x = x
self.y = y
self.minProx = minProx
class coOrd:
def __init__(self, x, y, minProx):
self.x = x
self.y = y
self.minProx = minProx
def checkProx(self, coOrdToChk:coOrd)->bool:
proximity = math.sqrt((self.x - coOrdToChk.x)**2 + (self.x - coOrdToChk.x)**2)
if proximity < self.minProx or proximity < coOrdToChk.minProx:
return False
return True
Is there another way to do this, or am I just wanting a feature that doesn't exist?

how to make a temporary object from withing the class function in python?

I'm writing this code and there is a need to send objects as parameters in functions. My problem is one of the objects needs to be resued with its original values but as I need to return an object from the functions.
I don't know how I can send the answer and keep the original values in the object
safe for reuse. Is there any way to make an object from the class declaration itself?
import math
class Points(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __sub__(self, no):
no.x = no.x - self.x
no.y = no.y - self.y
no.z = no.z - self.z
return(no)
def dot(self, no):
ans = (self.x * no.x)+(self.y * no.y)+(self.z * no.z)
return ans
def cross(self, no):
x = (self.y * no.z)-(self.z * no.y)
y = (self.x * no.z)-(self.z * no.x)
z = (self.x * no.y)-(self.y * no.x)
self.x = x
self.y = y
self.z = z
return(self)
def absolute(self):
return pow((self.x ** 2 + self.y ** 2 + self.z ** 2), 0.5)
if __name__ == '__main__':
points = list()
for i in range(4):
a = list(map(float, input().split()))
points.append(a)
a, b, c, d = Points(*points[0]), Points(*points[1]), Points(*points[2]), Points(*points[3])
x = (b - a).cross(c - b)
y = (c - b).cross(d - c)
angle = math.acos(x.dot(y) / (x.absolute() * y.absolute()))
print("%.2f" % math.degrees(angle))
I want to do something like:
def function_name(self,other)
temp.x = self.x + other.x
temp.y = self.y + other.y
return temp
This way both input objects will have their original values but I don't know how to get that temp.
Thanks everyone who helped. I got the answer to what I was looking. I wanted an object to act as a container that can store the class variables,
and I didn't knew I can just make a new object of the class from within it!
import math
class Points(object):
def __init__(self, x, y, z):
self.x=x
self.y=y
self.z=z
def __sub__(self, no):
return Points((self.x-no.x),(self.y-no.y),(self.z-no.z))
def dot(self, no):
return (self.x*no.x)+(self.y*no.y)+(self.z*no.z)
def cross(self, no):
return Points((self.y*no.z-self.z*no.y),(self.z*no.x-self.x*no.z),(self.x*no.y-self.y*no.x))
def absolute(self):
return pow((self.x ** 2 + self.y ** 2 + self.z ** 2), 0.5)
As you can see using points, i.e the constructor for class Points, I can store the result of any operations and can return it as an object while not altering my input objects.
If what you're trying to do is reuse a variable that you have passed to a class object, you can just duplicate it in your __init__ statement, or in the function where you use it.
e.g
class Foo:
def __init__(self, my_var1, my_var2):
self.my_var1 = my_var1
self.my_var2 = my_var2
def bar(self):
bar_var1 = self.my_var1
bar_var2 = self.my_var2
bar_var1 = bar_var1 + bar_var2
return bar_var1
Although, I am a little confused by why you are attempting to return self in your cross function, as self is a class parameter, and you don't seem to be using it in its intended purpose. If you're confused about how you should be using self, a brief read through the python class tutorial might be helpful. However, barring that, I hope this answers your question.

How to call class constructor having its name in text variable? [Python]

Let's assume we have some classes defined and available in global namespace. In example:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Vector:
def __init__(self, alpha, r):
self.x = r * cos(alpha)
self.y = r * sin(alpha)
# and many others...
How to do this:
class_name = 'Point'
x = 14.361
y = -8.100
code_str = 'class_object = ' + class_name + '(' + str(x) + ', ' + str(y) + ')'
exec code_str # That evaluates to: "class_object = Point(14.361, -8.100)"
print class_object.x, class_object.y
without using the dangerous exec?
PS. I'm intending to load the data from some txt or json file if anyone asks.
If the class is defined or imported in the same module, you could use something like :
globals()[class_name](x, y)
if you have many classes to handle, you should better use a dictionnary to store them, key is the name, value is the class,
then you can call it with :
my_classes = {'Point' : Point, 'Point2' : Point2}
class_name = 'Point'
x = 14.361
y = -8.100
my_classes[class_name](x, y)
Provided that a class is defined in (or imported into) the global namespace, you can get a reference to it via the dictionary returned by globals(). After that just create an instance the usual way, e.g.:
class_name = 'Point'
kwargs = {'x': 14.361, 'y': -8.100}
Point = globals()[class_name]
point = Point(**kwargs)
You can use eval.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Vector:
def __init__(self, x, y):
self.x = x+100
self.y = y+100
class_name = 'Vector'
x = 10
y = 20
caller = '{}({},{})'.format(class_name,x,y)
ob = eval(caller)
print ob.x, ob.y

Create a picklable Python class

I am trying to create some custom Python classes for my application. When I try to debug my code I can not pick the instances of my custom classes, I receive the error "Object XXX is not picklable".
I found this page https://docs.python.org/3/library/pickle.html#what-can-be-pickled-and-unpickled but I don't understand how I should implement the methods that make my class picklable.
For example how would you modify the following classes so that I can pick instances of them?
class Point3D:
def __init__ (self, x, y, z):
self.x = x
self.y = y
self.z = z
def move(self, vector):
self.x += vector.x
self.y += vector.y
self.z += vector.z
return
def isValidPoint(self):
isNotValid = False
isNotValid = math.isnan(self.x) or math.isnan(self.y) or math.isnan(self.z)
return not isNotValid
And
class PointCloud3D:
def __init__ (self):
self.points = []
def getNumberOfPoints(self):
return len(self.points)
def addPoint(self, point):
self.points.append(point)
return
def addPointCloud3D(self, additionalPointCloud3D):
for self.point in additionalPointCloud3D:
self.addPoint(point)
def getCloudCenter(self):
numberOfPoints = self.getNumberOfPoints()
centersSumX = 0
centersSumY = 0
centersSumZ = 0
for point in self.points:
centersSumX = centersSumX + point.x
centersSumY = centersSumY + point.y
centersSumZ = centersSumZ + point.z
centerX = centersSumX/numberOfPoints
centerY = centersSumY/numberOfPoints
centerZ = centersSumZ/numberOfPoints
center = Point3D(float(centerX), float(centerY) , float(centerZ))
return center
While here you can find the code that I am trying to debug:
from classDatabase import Point3D, PointCloud3D
testPoint1 = Point3D(1.5, 0.2, 2.3)
testPoint2 = Point3D(3.5, 1.2, 5.3)
testPointCloud3D = PointCloud3D()
testPointCloud3D.addPoint(testPoint1)
testPointCloud3D.addPoint(testPoint2)
Finally a screenshot of the issue:

Changed all objects value in list in object changed instead of only one

I have problem with my program. When I try to change object value (which is in list) I changed all object's value in that list.
My code:
class obj:
def __init__(self, x, y):
self.x = x
self.y = y
def mirrorise(self, mirror):
self.mirror = mirror
if self.mirror.type == 'teleporterx':
self.x -= (self.x-(self.mirror.x+self.mirror.x1/2))*2
class person(obj):
def __init__(self, x, y):
self.x = x
self.y = y
self.pos = [obj(self.x, self.y)]
def mirrored(self, mirrors):
self.count = 0
self.mirrors = mirrors
self.mens = 0
for men in self.pos:
self.mens += 1
for mirror in self.mirrors:
if self.count == 1:
for men in range(self.mens):
self.pos.append(self.pos[men])
self.count = 1
self.count = 0
for men in self.pos:
men.mirrorise(self.mirrors[self.count])
self.count += 1
if self.mirrors[self.count-1] == self.mirrors[-1]:
self.count = 0
class mirror:
def __init__(self, x, y, x1, y1, type):
self.x = x
self.y = y
self.x1 = x1
self.y1 = y1
self.type = type
After in code I call person object called I and two mirror objects called mirr and mirr2 with type teleportx. When I write:
I.mirrored([mirr, mirr2])
it changes x for all objects in I.pos. If I write
I.pos[3].mirrorise(mirr)
it still changes all x. Even if I write:
I.pos[3].x -= (I.pos[3].x-(mirr2.x+mirr.x1/2))*2
it changes all values. So, is it some Python rule or I have mistake?
You are adding references to your one original obj() instance:
self.pos.append(self.pos[men])
That's not a copy; that's just another reference to the same object.
Create a new obj() instance instead:
self.pos.append(obj(self.pos[men].x, self.pos[men].y))

Categories

Resources