-5

This is a part of a code

class Object1:
    def __init__(self):
        mu = np.linspace(1.65, 1.8, num = 50)
        self.mu=mu

I need to call mu attribute out of class.

What I tried:

a=getattr(Object1,'mu')
a=Object1.mu

Edit: I explain in a better way the problem and the solution.

I apologize for not posting all the code from the beginning, but I can't (I'll post a part of it) and because of that my question was misunderstood, I'll post the solution anyway and ask the question again.

import scipy.stats as sts
import numpy as np
import matplotlib.pyplot as plt
import scipy as sp

class Object1:
    def __init__(self):
        """
        Variables and distributions.

        Returns
        -------
        None.

        """
        mu = np.linspace(1.65, 1.8, num = 50)
        self.mu=mu
        uniform_dist = sts.uniform.pdf(mu) + 1 #sneaky advanced note: I'm using the uniform distribution for clarity, but we can also make the beta distribution look completely flat by tweaking alpha and beta!
        self.uniform_dist=uniform_dist
        beta_dist = sts.beta.pdf(mu, 2, 5, loc = 1.65, scale = 0.2) 
        self.beta_dist =beta_dist 

    def normalization(self,distr):
        return distr/distr.sum()

How I was calling the attributes:

a=Object1.mu

then I tried:

a=Object1().mu

Explanation: To call the normalization() method, I must call it on an object, and not on the class. That is what is failing, because when I do object.method(parameters), Python translates it to Class.method(object, parameters), making the object in question become self within the method. Calling it like Class.method(parameters), which is what I did, would result in a missing parameter in the call (python can't tell which one and assumes it's distr, but actually it was the first one, self).

Solution:

bayesian=Object1()

uniform_distribution=bayesian.uniform_dist
beta_distribution=bayesian.beta_dist

uniform_dist=bayesian.normalization(uniform_distribution)
beta_dist=bayesian.normalization(beta_distribution)
Strovic
  • 73
  • 5
  • 4
    It is an attribute of an instance, not the class itself. You need to read more tutorials to get the concepts of classes and objects – azro Dec 29 '22 at 21:46
  • 1
    The class has no attribute `mu`, the error message is right. – mkrieger1 Dec 29 '22 at 21:46
  • 2
    This code only makes sense if you create an instance of `Object1`, rather than trying to act on the class itself. E.g. `ob = Object1(); a = ob.mu` – Tom Karzes Dec 29 '22 at 21:48
  • https://stackoverflow.com/questions/2714573/instance-variables-vs-class-variables-in-python – Pranav Hosangadi Dec 29 '22 at 21:51

1 Answers1

0

You can use the mu as a static variable

class Object1:
    mu = np.linspace(1.65, 1.8, num = 50)
    
    def __init__(self):
        pass
tomerar
  • 805
  • 5
  • 10